repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/enablers/package.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.scalatest
package object enablers {
@deprecated("Please use org.scalactic.enablers.Collecting instead.")
type Collecting[E, C] = org.scalactic.enablers.Collecting[E, C]
@deprecated("Please use org.scalactic.enablers.Definition instead.")
type Definition[-T] = org.scalactic.enablers.Definition[T]
type EvidenceThat[T] = org.scalactic.enablers.EvidenceThat[T] // TODO, just change all these
@deprecated("Please use org.scalactic.enablers.Emptiness instead.")
type Emptiness[-T] = org.scalactic.enablers.Emptiness[T]
@deprecated("Please use org.scalactic.enablers.Existence instead.")
type Existence[-S] = org.scalactic.enablers.Existence[S]
@deprecated("Please use org.scalactic.enablers.Length instead.")
type Length[T] = org.scalactic.enablers.Length[T]
@deprecated("Please use org.scalactic.enablers.Messaging instead.")
type Messaging[T] = org.scalactic.enablers.Messaging[T]
@deprecated("Please use org.scalactic.enablers.Readability instead.")
type Readability[-T] = org.scalactic.enablers.Readability[T]
@deprecated("Please use org.scalactic.enablers.Size instead.")
type Size[T] = org.scalactic.enablers.Size[T]
@deprecated("Please use org.scalactic.enablers.Sortable instead.")
type Sortable[-S] = org.scalactic.enablers.Sortable[S]
@deprecated("Please use org.scalactic.enablers.Writability instead.")
type Writability[-T] = org.scalactic.enablers.Writability[T]
}
|
cquiroz/scalatest | common-test.js/src/main/scala/org/scalatest/LineNumberHelper.scala | <reponame>cquiroz/scalatest
package org.scalatest
private[scalatest] trait LineNumberHelper {
def thisLineNumber = {
val st = Thread.currentThread.getStackTrace
st.dropWhile(_.getFileName.startsWith("https://")).dropWhile(e => e.getFileName.endsWith("LineNumberHelper.scala") || e.getFileName.endsWith("SharedHelpers.scala")).head.getLineNumber
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/fixture/AsyncFlatSpecLikeSpec.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.fixture
import scala.concurrent.{Future, ExecutionContext}
import org.scalatest._
import SharedHelpers.EventRecordingReporter
class AsyncFlatSpecLikeSpec extends org.scalatest.FunSpec {
describe("AsyncFlatSpecLike") {
it("can be used for tests that return Future") {
class ExampleSpec extends AsyncFlatSpecLike {
implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global
type FixtureParam = String
def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
test("testing")
val a = 1
it should "test 1" in { fixture =>
Future {
assert(a == 1)
}
}
it should "test 2" in { fixture =>
Future {
assert(a == 2)
}
}
it should "test 3" in { fixture =>
Future {
pending
}
}
it should "test 4" in { fixture =>
Future {
cancel
}
}
it should "test 5" ignore { fixture =>
Future {
cancel
}
}
override def newInstance = new ExampleSpec
}
val rep = new EventRecordingReporter
val spec = new ExampleSpec
val status = spec.run(None, Args(reporter = rep))
status.waitUntilCompleted()
assert(rep.testStartingEventsReceived.length == 4)
assert(rep.testSucceededEventsReceived.length == 1)
assert(rep.testSucceededEventsReceived(0).testName == "should test 1")
assert(rep.testFailedEventsReceived.length == 1)
assert(rep.testFailedEventsReceived(0).testName == "should test 2")
assert(rep.testPendingEventsReceived.length == 1)
assert(rep.testPendingEventsReceived(0).testName == "should test 3")
assert(rep.testCanceledEventsReceived.length == 1)
assert(rep.testCanceledEventsReceived(0).testName == "should test 4")
assert(rep.testIgnoredEventsReceived.length == 1)
assert(rep.testIgnoredEventsReceived(0).testName == "should test 5")
}
it("can be used for tests that did not return Future") {
class ExampleSpec extends AsyncFlatSpecLike {
implicit val executionContext: ExecutionContext = ExecutionContext.Implicits.global
type FixtureParam = String
def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] =
test("testing")
val a = 1
it should "test 1" in { fixture =>
assert(a == 1)
}
it should "test 2" in { fixture =>
assert(a == 2)
}
it should "test 3" in { fixture =>
pending
}
it should "test 4" in { fixture =>
cancel
}
it should "test 5" ignore { fixture =>
cancel
}
override def newInstance = new ExampleSpec
}
val rep = new EventRecordingReporter
val spec = new ExampleSpec
val status = spec.run(None, Args(reporter = rep))
status.waitUntilCompleted()
assert(rep.testStartingEventsReceived.length == 4)
assert(rep.testSucceededEventsReceived.length == 1)
assert(rep.testSucceededEventsReceived(0).testName == "should test 1")
assert(rep.testFailedEventsReceived.length == 1)
assert(rep.testFailedEventsReceived(0).testName == "should test 2")
assert(rep.testPendingEventsReceived.length == 1)
assert(rep.testPendingEventsReceived(0).testName == "should test 3")
assert(rep.testCanceledEventsReceived.length == 1)
assert(rep.testCanceledEventsReceived(0).testName == "should test 4")
assert(rep.testIgnoredEventsReceived.length == 1)
assert(rep.testIgnoredEventsReceived(0).testName == "should test 5")
}
}
} |
cquiroz/scalatest | scalatest.js/src/main/scala/org/scalatest/tools/Framework.scala | package org.scalatest.tools
import org.scalatest.{Tracker, Reporter}
import org.scalatest.events.{ExceptionalEvent, Summary}
import sbt.testing.{Framework => BaseFramework, Event => SbtEvent, Status => SbtStatus, _}
import scala.collection.mutable.ListBuffer
import scala.compat.Platform
class Framework extends BaseFramework {
def name: String = "ScalaTest"
def fingerprints: Array[Fingerprint] =
Array(
new SubclassFingerprint {
def superclassName = "org.scalatest.Suite"
def isModule = false
def requireNoArgConstructor = true
})
def slaveRunner(args: Array[String], remoteArgs: Array[String], testClassLoader: ClassLoader, send: (String) => Unit): Runner =
new SlaveRunner(args, remoteArgs, testClassLoader, send)
def runner(args: Array[String], remoteArgs: Array[String], testClassLoader: ClassLoader): Runner =
new MasterRunner(args, remoteArgs, testClassLoader)
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/fixture/PropSpec.scala | <filename>scalatest/src/main/scala/org/scalatest/fixture/PropSpec.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.fixture
import org.scalatest._
import scala.collection.immutable.ListSet
import org.scalatest.Suite.autoTagClassAnnotations
/**
* A sister class to <code>org.scalatest.PropSpec</code> that can pass a fixture object into its tests.
*
* <table><tr><td class="usage">
* <strong>Recommended Usage</strong>:
* Use class <code>fixture.PropSpec</code> in situations for which <a href="../PropSpec.html"><code>PropSpec</code></a>
* would be a good choice, when all or most tests need the same fixture objects
* that must be cleaned up afterwards. <em>Note: <code>fixture.PropSpec</code> is intended for use in special
* situations, with class <code>PropSpec</code> used for general needs. For
* more insight into where <code>fixture.PropSpec</code> fits in the big picture, see
* the <a href="../PropSpec.html#withFixtureOneArgTest"><code>withFixture(OneArgTest)</code></a> subsection of
* the <a href="../PropSpec.html#sharedFixtures">Shared fixtures</a> section in the documentation for class <code>PropSpec</code>.</em>
* </td></tr></table>
*
* <p>
* Class <code>fixture.PropSpec</code> behaves similarly to class <code>org.scalatest.PropSpec</code>, except that tests may have a
* fixture parameter. The type of the
* fixture parameter is defined by the abstract <code>FixtureParam</code> type, which is a member of this class.
* This class also has an abstract <code>withFixture</code> method. This <code>withFixture</code> method
* takes a <code>OneArgTest</code>, which is a nested trait defined as a member of this class.
* <code>OneArgTest</code> has an <code>apply</code> method that takes a <code>FixtureParam</code>.
* This <code>apply</code> method is responsible for running a test.
* This class's <code>runTest</code> method delegates the actual running of each test to <code>withFixture</code>, passing
* in the test code to run via the <code>OneArgTest</code> argument. The <code>withFixture</code> method (abstract in this class) is responsible
* for creating the fixture argument and passing it to the test function.
* </p>
*
* <p>
* Subclasses of this class must, therefore, do three things differently from a plain old <code>org.scalatest.PropSpec</code>:
* </p>
*
* <ol>
* <li>define the type of the fixture parameter by specifying type <code>FixtureParam</code></li>
* <li>define the <code>withFixture(OneArgTest)</code> method</li>
* <li>write tests that take a fixture parameter</li>
* <li>(You can also define tests that don't take a fixture parameter.)</li>
* </ol>
*
* <p>
* Here's an example:
* </p>
*
* <pre class="stHighlight">
* package org.scalatest.examples.fixture.propspec
*
* import org.scalatest._
* import prop.PropertyChecks
* import java.io._
*
* class ExampleSpec extends fixture.PropSpec with PropertyChecks with ShouldMatchers {
*
* // 1. define type FixtureParam
* type FixtureParam = FileReader
*
* // 2. define the withFixture method
* def withFixture(test: OneArgTest) = {
*
* val FileName = "TempFile.txt"
*
* // Set up the temp file needed by the test
* val writer = new FileWriter(FileName)
* try {
* writer.write("Hello, test!")
* }
* finally {
* writer.close()
* }
*
* // Create the reader needed by the test
* val reader = new FileReader(FileName)
*
* try {
* // Run the test using the temp file
* test(reader)
* }
* finally {
* // Close and delete the temp file
* reader.close()
* val file = new File(FileName)
* file.delete()
* }
* }
*
* // 3. write property-based tests that take a fixture parameter
* // (Hopefully less contrived than the examples shown here.)
* property("can read from a temp file") { reader =>
* var builder = new StringBuilder
* var c = reader.read()
* while (c != -1) {
* builder.append(c.toChar)
* c = reader.read()
* }
* val fileContents = builder.toString
* forAll { (c: Char) =>
* whenever (c != 'H') {
* fileContents should not startWith c.toString
* }
* }
* }
*
* property("can read the first char of the temp file") { reader =>
* val firstChar = reader.read()
* forAll { (c: Char) =>
* whenever (c != 'H') {
* c should not equal firstChar
* }
* }
* }
*
* // (You can also write tests that don't take a fixture parameter.)
* property("can write tests that don't take the fixture") { () =>
* forAll { (i: Int) => i + i should equal (2 * i) }
* }
* }
* </pre>
*
* <p>
* Note: to run the examples on this page, you'll need to include <a href="http://www.scalacheck.org">ScalaCheck</a> on the classpath in addition to ScalaTest.
* </p>
*
* <p>
* In the previous example, <code>withFixture</code> creates and initializes a temp file, then invokes the test function,
* passing in a <code>FileReader</code> connected to that file. In addition to setting up the fixture before a test,
* the <code>withFixture</code> method also cleans it up afterwards. If you need to do some clean up
* that must happen even if a test fails, you should invoke the test function from inside a <code>try</code> block and do
* the cleanup in a <code>finally</code> clause, as shown in the previous example.
* </p>
*
* <p>
* If a test fails, the <code>OneArgTest</code> function will result in a [[org.scalatest.Failed Failed]] wrapping the
* exception describing the failure.
* The reason you must perform cleanup in a <code>finally</code> clause is that in case an exception propagates back through
* <code>withFixture</code>, the <code>finally</code> clause will ensure the fixture cleanup happens as that exception
* propagates back up the call stack to <code>runTest</code>.
* </p>
*
* <p>
* If a test doesn't need the fixture, you can indicate that by providing a no-arg instead of a one-arg function.
* In other words, instead of starting your function literal
* with something like “<code>reader =></code>”, you'd start it with “<code>() =></code>”, as is done
* in the third test in the above example. For such tests, <code>runTest</code>
* will not invoke <code>withFixture(OneArgTest)</code>. It will instead directly invoke <code>withFixture(NoArgTest)</code>.
* </p>
*
* <a name="multipleFixtures"></a>
* <h2>Passing multiple fixture objects</h2>
*
* <p>
* If the fixture you want to pass into your tests consists of multiple objects, you will need to combine
* them into one object to use this class. One good approach to passing multiple fixture objects is
* to encapsulate them in a case class. Here's an example:
* </p>
*
* <pre class="stHighlight">
* case class FixtureParam(builder: StringBuilder, buffer: ListBuffer[String])
* </pre>
*
* <p>
* To enable the stacking of traits that define <code>withFixture(NoArgTest)</code>, it is a good idea to let
* <code>withFixture(NoArgTest)</code> invoke the test function instead of invoking the test
* function directly. To do so, you'll need to convert the <code>OneArgTest</code> to a <code>NoArgTest</code>. You can do that by passing
* the fixture object to the <code>toNoArgTest</code> method of <code>OneArgTest</code>. In other words, instead of
* writing “<code>test(theFixture)</code>”, you'd delegate responsibility for
* invoking the test function to the <code>withFixture(NoArgTest)</code> method of the same instance by writing:
* </p>
*
* <pre>
* withFixture(test.toNoArgTest(theFixture))
* </pre>
*
* <p>
* Here's a complete example:
* </p>
*
* <pre class="stHighlight">
* package org.scalatest.examples.fixture.propspec.multi
*
* import org.scalatest._
* import prop.PropertyChecks
* import scala.collection.mutable.ListBuffer
*
* class ExampleSpec extends fixture.PropSpec with PropertyChecks with ShouldMatchers {
*
* case class FixtureParam(builder: StringBuilder, buffer: ListBuffer[String])
*
* def withFixture(test: OneArgTest) = {
*
* // Create needed mutable objects
* val stringBuilder = new StringBuilder("ScalaTest is ")
* val listBuffer = new ListBuffer[String]
* val theFixture = FixtureParam(stringBuilder, listBuffer)
*
* // Invoke the test function, passing in the mutable objects
* withFixture(test.toNoArgTest(theFixture))
* }
*
* property("testing should be easy") { f =>
* f.builder.append("easy!")
* assert(f.builder.toString === "ScalaTest is easy!")
* assert(f.buffer.isEmpty)
* val firstChar = f.builder(0)
* forAll { (c: Char) =>
* whenever (c != 'S') {
* c should not equal firstChar
* }
* }
* f.buffer += "sweet"
* }
*
* property("testing should be fun") { f =>
* f.builder.append("fun!")
* assert(f.builder.toString === "ScalaTest is fun!")
* assert(f.buffer.isEmpty)
* val firstChar = f.builder(0)
* forAll { (c: Char) =>
* whenever (c != 'S') {
* c should not equal firstChar
* }
* }
* }
* }
* </pre>
*
* @author <NAME>
*/
@Finders(Array("org.scalatest.finders.PropSpecFinder"))
abstract class PropSpec extends PropSpecLike {
/**
* Returns a user friendly string for this suite, composed of the
* simple name of the class (possibly simplified further by removing dollar signs if added by the Scala interpeter) and, if this suite
* contains nested suites, the result of invoking <code>toString</code> on each
* of the nested suites, separated by commas and surrounded by parentheses.
*
* @return a user-friendly string for this suite
*/
override def toString: String = Suite.suiteToString(None, this)
}
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/algebra/MonoidSpec.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.algebra
import org.scalactic.UnitSpec
class MonoidSpec extends UnitSpec {
val listMonoid = new Monoid[List[_]] {
def z: List[_] = Nil
def op(xs: List[_], ys: List[_]): List[_] = xs ++ ys
}
def listMonoidTyped[A] = new Monoid[List[A]] {
def z: List[A] = Nil
def op(xs: List[A], ys: List[A]): List[A] = xs ++ ys
}
val additionMonoid = new Monoid[Int] {
def z: Int = 0
def op(a1: Int, a2: Int): Int = a1 + a2
}
"The list monoid of any type " should " have a binaray associative op" in {
val as = List(1,2,3)
val bs = List("five","six")
val cs = List(10)
val op: (List[_], List[_]) => List[Any] = listMonoid.op _
op( as, op(bs, cs) ) shouldEqual op( op(as, bs), cs )
}
"The list monoid " should " have a binaray associative op that supports infix notation" in {
import Monoid.adapters
implicit val monoid = listMonoidTyped[Int]
val as = List(1,2,3)
val bs = List(5,6)
val cs = List(10)
((as op bs) op cs) shouldEqual (as op (bs op cs))
}
"The list monoid " should " have a zero element that is a left identity and right identity" in {
import Monoid.adapters
implicit val monoid = listMonoidTyped[Int]
val as = List(1,2,3)
(as op monoid.z) shouldEqual as
(monoid.z op as) shouldEqual as
}
"The list monoid " should " be foldable over a collections of types " in {
val lists = List(List(1,2,3), List(4,5,6), List(7,8))
val foldResult: List[Any] = lists.fold(listMonoid.z)(listMonoid.op)
foldResult shouldEqual List(1,2,3,4,5,6,7,8)
}
"The addition monoid " should " have a binary associative op " in {
import Monoid.adapters
implicit val monoid = additionMonoid
val x = 80
val y = 86
val z = 70
((x op y) op z) shouldEqual (x op (y op z))
}
"The addition monoid " should " have a zero element, i.e. an identity element." in {
import Monoid.adapters
implicit val monoid = additionMonoid
val x = 8086
(x op monoid.z) shouldEqual x
}
"The addition monoid's op and zero element " should " enable summing over a List of ints " in {
val m = additionMonoid
val listInts = List(1,4,5,10)
val foldResult = listInts.fold(m.z)(m.op)
foldResult shouldEqual 20
}
"Monoid" should "provide an parameterless apply method in its companion to summon an implicit" in {
implicit val monoid = listMonoidTyped[Int]
monoid should be theSameInstanceAs implicitly[Monoid[List[Int]]]
monoid should be theSameInstanceAs Monoid[List[Int]]
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldBeWritableSpec.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 SharedHelpers.{createTempDirectory, thisLineNumber}
import java.io.File
import Matchers._
import exceptions.TestFailedException
class ShouldBeWritableSpec extends Spec {
val tempDir = createTempDirectory()
val writableFile = File.createTempFile("writable", "me", tempDir)
writableFile.setWritable(true)
val secretFile = new File(tempDir, "secret")
secretFile.setWritable(false)
val fileName: String = "ShouldBeWritableSpec.scala"
def wasNotWritable(left: Any): String =
FailureMessages.wasNotWritable(left)
def wasWritable(left: Any): String =
FailureMessages.wasWritable(left)
def `writableFile should be writable, secretFile should not be writable` {
assert(writableFile.canRead === true)
assert(secretFile.canRead === false)
}
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 `writable matcher` {
object `when work with 'file should be (writable)'` {
def `should do nothing when file is writable` {
writableFile should be (writable)
}
def `should throw TestFailedException with correct stack depth when file is not writable` {
val caught1 = intercept[TestFailedException] {
secretFile should be (writable)
}
assert(caught1.message === Some(wasNotWritable(secretFile)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'file should not be writable'` {
def `should do nothing when file is not writable` {
secretFile should not be writable
}
def `should throw TestFailedException with correct stack depth when file is writable` {
val caught1 = intercept[TestFailedException] {
writableFile should not be writable
}
assert(caught1.message === Some(wasWritable(writableFile)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'file shouldBe writable'` {
def `should do nothing when file is writable` {
writableFile shouldBe writable
}
def `should throw TestFailedException with correct stack depth when file is not writable` {
val caught1 = intercept[TestFailedException] {
secretFile shouldBe writable
}
assert(caught1.message === Some(wasNotWritable(secretFile)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'file shouldNot be (writable)'` {
def `should do nothing when file is not writable` {
secretFile shouldNot be (writable)
}
def `should throw TestFailedException with correct stack depth when file is writable` {
val caught1 = intercept[TestFailedException] {
writableFile shouldNot be (writable)
}
assert(caught1.message === Some(wasWritable(writableFile)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'all(xs) should be (writable)'` {
def `should do nothing when all(xs) is writable` {
all(List(writableFile)) should be (writable)
}
def `should throw TestFailedException with correct stack depth when all(xs) is not writable` {
val left1 = List(secretFile)
val caught1 = intercept[TestFailedException] {
all(left1) should be (writable)
}
assert(caught1.message === Some(allError(left1, wasNotWritable(secretFile), thisLineNumber - 2)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'all(xs) should not be writable'` {
def `should do nothing when all(xs) is not writable` {
all(List(secretFile)) should not be writable
}
def `should throw TestFailedException with correct stack depth when all(xs) is writable` {
val left1 = List(writableFile)
val caught1 = intercept[TestFailedException] {
all(left1) should not be writable
}
assert(caught1.message === Some(allError(left1, wasWritable(writableFile), thisLineNumber - 2)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'all(xs) shouldBe writable'` {
def `should do nothing when all(xs) is writable` {
all(List(writableFile)) shouldBe writable
}
def `should throw TestFailedException with correct stack depth when all(xs) is not writable` {
val left1 = List(secretFile)
val caught1 = intercept[TestFailedException] {
all(left1) shouldBe writable
}
assert(caught1.message === Some(allError(left1, wasNotWritable(secretFile), thisLineNumber - 2)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `when work with 'all(xs) shouldNot be (writable)'` {
def `should do nothing when all(xs) is not writable` {
all(List(secretFile)) shouldNot be (writable)
}
def `should throw TestFailedException with correct stack depth when all(xs) is writable` {
val left1 = List(writableFile)
val caught1 = intercept[TestFailedException] {
all(left1) shouldNot be (writable)
}
assert(caught1.message === Some(allError(left1, wasWritable(writableFile), thisLineNumber - 2)))
assert(caught1.failedCodeFileName === Some(fileName))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
}
}
|
cquiroz/scalatest | scalactic-macro/src/main/scala/org/scalactic/anyvals/PosZDouble.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>Double</code> value underlying this <code>PosZDouble</code>.
*/
final class PosZDouble private (val value: Double) extends AnyVal {
/**
* A string representation of this <code>PosZDouble</code>.
*/
override def toString: String = s"PosZDouble($value)"
/**
* Converts this <code>PosZDouble</code> to a <code>Byte</code>.
*/
def toByte: Byte = value.toByte
/**
* Converts this <code>PosZDouble</code> to a <code>Short</code>.
*/
def toShort: Short = value.toShort
/**
* Converts this <code>PosZDouble</code> to a <code>Char</code>.
*/
def toChar: Char = value.toChar
/**
* Converts this <code>PosZDouble</code> to an <code>Int</code>.
*/
def toInt: Int = value.toInt
/**
* Converts this <code>PosZDouble</code> to a <code>Long</code>.
*/
def toLong: Long = value.toLong
/**
* Converts this <code>PosZDouble</code> to a <code>Float</code>.
*/
def toFloat: Float = value.toFloat
/**
* Converts this <code>PosZDouble</code> to a <code>Double</code>.
*/
def toDouble: Double = value.toDouble
/** Returns this value, unmodified. */
def unary_+ : PosZDouble = this
/** Returns the negation of this value. */
def unary_- : Double = -value
/**
* Converts this <code>PosZDouble</code>'s value to a string then concatenates the given string.
*/
def +(x: String): String = 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 sum of this value and `x`. */
def +(x: Byte): Double = value + x
/** Returns the sum of this value and `x`. */
def +(x: Short): Double = value + x
/** Returns the sum of this value and `x`. */
def +(x: Char): Double = value + x
/** Returns the sum of this value and `x`. */
def +(x: Int): Double = value + x
/** Returns the sum of this value and `x`. */
def +(x: Long): Double = value + x
/** Returns the sum of this value and `x`. */
def +(x: Float): Double = 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): Double = value - x
/** Returns the difference of this value and `x`. */
def -(x: Short): Double = value - x
/** Returns the difference of this value and `x`. */
def -(x: Char): Double = value - x
/** Returns the difference of this value and `x`. */
def -(x: Int): Double = value - x
/** Returns the difference of this value and `x`. */
def -(x: Long): Double = value - x
/** Returns the difference of this value and `x`. */
def -(x: Float): Double = 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): Double = value * x
/** Returns the product of this value and `x`. */
def *(x: Short): Double = value * x
/** Returns the product of this value and `x`. */
def *(x: Char): Double = value * x
/** Returns the product of this value and `x`. */
def *(x: Int): Double = value * x
/** Returns the product of this value and `x`. */
def *(x: Long): Double = value * x
/** Returns the product of this value and `x`. */
def *(x: Float): Double = 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): Double = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Short): Double = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Char): Double = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Int): Double = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Long): Double = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Float): Double = 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): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Short): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Char): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Int): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Long): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Float): Double = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Double): Double = value % x
// Stuff from RichDouble
def isPosInfinity: Boolean = Double.PositiveInfinity == value
def max(that: PosZDouble): PosZDouble = if (math.max(value, that.value) == value) this else that
def min(that: PosZDouble): PosZDouble = if (math.min(value, that.value) == value) this else that
def isWhole = {
val longValue = value.toLong
longValue.toDouble == value || longValue == Long.MaxValue && value < Double.PositiveInfinity || longValue == Long.MinValue && value > Double.NegativeInfinity
}
def round: PosZLong = PosZLong.from(math.round(value)).get
def ceil: PosZDouble = PosZDouble.from(math.ceil(value)).get
def floor: PosZDouble = PosZDouble.from(math.floor(value)).get
/** Converts an angle measured in degrees to an approximately equivalent
* angle measured in radians.
*
* @return the measurement of the angle x in radians.
*/
def toRadians: Double = math.toRadians(value)
/** Converts an angle measured in radians to an approximately equivalent
* angle measured in degrees.
* @return the measurement of the angle x in degrees.
*/
def toDegrees: Double = math.toDegrees(value)
// adapted from RichInt:
/**
* @param end The final bound of the range to make.
* @return A [[scala.collection.immutable.Range.Partial[Double, NumericRange[Double]]]] from `this` up to but
* not including `end`.
*/
def until(end: Double): Range.Partial[Double, NumericRange[Double]] =
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[Double]]] from `this` up to but
* not including `end`.
*/
def until(end: Double, step: Double): NumericRange.Exclusive[Double] =
value.until(end, step)
/**
* @param end The final bound of the range to make.
* @return A [[scala.collection.immutable.Range.Partial[Double, NumericRange[Double]]]] from `'''this'''` up to
* and including `end`.
*/
def to(end: Double): Range.Partial[Double, NumericRange[Double]] =
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[Double]]] from `'''this'''` up to
* and including `end`.
*/
def to(end: Double, step: Double): NumericRange.Inclusive[Double] =
value.to(end, step)
}
object PosZDouble {
def from(value: Double): Option[PosZDouble] =
if (value >= 0.0) Some(new PosZDouble(value)) else None
import language.experimental.macros
import scala.language.implicitConversions
implicit def apply(value: Double): PosZDouble = macro PosZDoubleMacro.apply
implicit def widenToDouble(poz: PosZDouble): Double = poz.value
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/UncheckedEquality.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 EqualityPolicy._
/**
* Provides <code>===</code> and <code>!==</code> operators that return <code>Boolean</code>, delegate the equality determination
* to an <code>Equality</code> type class, and require no relationship between the types of the two values compared.
*
* <table><tr><td class="usage">
* <strong>Recommended Usage</strong>:
* Trait <code>UncheckedEquality</code> is useful (in both production and test code) when you need determine equality for a type of object differently than its
* <code>equals</code> method: either you can't change the <code>equals</code> method, or the <code>equals</code> method is sensible generally, but
* you are in a special situation where you need something else. If you also want a compile-time type check, however, you should use one
* of <code>UncheckedEquality</code> sibling traits:
* <a href="ConversionCheckedTripleEquals.html"><code>ConversionCheckedTripleEquals</code></a> or <a href="TypeCheckedTripleEquals.html"><code>TypeCheckedTripleEquals</code></a>.
* </td></tr></table>
*
* <p>
* This trait will override or hide implicit methods defined by its sibling traits,
* <a href="ConversionCheckedTripleEquals.html"><code>ConversionCheckedTripleEquals</code></a> or <a href="TypeCheckedTripleEquals.html"><code>TypeCheckedTripleEquals</code></a>,
* and can therefore be used to temporarily turn of type checking in a limited scope. Here's an example, in which <code>TypeCheckedTripleEquals</code> will
* cause a compiler error:
* </p>
*
* <pre class="stHighlight">
* import org.scalactic._
* import TypeCheckedTripleEquals._
*
* object Example {
*
* def cmp(a: Int, b: Long): Int = {
* if (a === b) 0 // This line won't compile
* else if (a < b) -1
* else 1
* }
*
* def cmp(s: String, t: String): Int = {
* if (s === t) 0
* else if (s < t) -1
* else 1
* }
* }
* </pre>
*
* Because <code>Int</code> and <code>Long</code> are not in a subtype/supertype relationship, comparing <code>1</code> and <code>1L</code> in the context
* of <code>TypeCheckedTripleEquals</code> will generate a compiler error:
* </p>
*
* <pre>
* Example.scala:9: error: types Int and Long do not adhere to the equality constraint selected for
* the === and !== operators; they must either be in a subtype/supertype relationship, or, if
* ConversionCheckedTripleEquals is in force, implicitly convertible in one direction or the other;
* the missing implicit parameter is of type org.scalactic.Constraint[Int,Long]
* if (a === b) 0 // This line won't compile
* ^
* one error found
* </pre>
*
* <p>
* You can “turn off” the type checking locally by importing the members of <code>UncheckedEquality</code> in
* a limited scope:
* </p>
*
* <pre class="stHighlight">
* package org.scalactic.examples.tripleequals
*
* import org.scalactic._
* import TypeCheckedTripleEquals._
*
* object Example {
*
* def cmp(a: Int, b: Long): Int = {
* import UncheckedEquality._
* if (a === b) 0
* else if (a < b) -1
* else 1
* }
*
* def cmp(s: String, t: String): Int = {
* if (s === t) 0
* else if (s < t) -1
* else 1
* }
* }
* </pre>
*
* <p>
* With the above change, the <code>Example.scala</code> file compiles fine. Type checking is turned off only inside the first <code>cmp</code> method that
* takes an <code>Int</code> and a <code>Long</code>. <code>TypeCheckedTripleEquals</code> is still enforcing its type constraint, for example, for the <code>s === t</code>
* expression in the other overloaded <code>cmp</code> method that takes strings.
* </p>
*
* <p>
* Because the methods in <code>UncheckedEquality</code> (and its siblings)<em>override</em> all the methods defined in
* supertype <a href="EqualityPolicy.html"><code>EqualityPolicy</code></a>, you can achieve the same
* kind of nested tuning of equality constraints whether you mix in traits, import from companion objects, or use some combination of both.
* </p>
*
* <p>
* In short, you should be able to select a primary constraint level via either a mixin or import, then change that in nested scopes
* however you want, again either through a mixin or import, without getting any implicit conversion ambiguity. The innermost constraint level in scope
* will always be in force.
* <p>
*
* @author <NAME>
*/
trait UncheckedEquality extends EqualityPolicy {
import scala.language.implicitConversions
// Inherit the Scaladoc for these methods
implicit override def convertToEqualizer[T](left: T): Equalizer[T] = new Equalizer(left)
override def convertToCheckingEqualizer[T](left: T): CheckingEqualizer[T] = new CheckingEqualizer(left)
override def convertToFreshCheckingEqualizer[T](left: T): FreshCheckingEqualizer[T] = new FreshCheckingEqualizer(left)
override def numericEqualityConstraint[A, B](implicit equalityOfA: Equality[A], numA: CooperatingNumeric[A], numB: CooperatingNumeric[B]): EqualityConstraint[A, B] with NativeSupport = new BasicEqualityConstraint[A, B](equalityOfA)
override def booleanEqualityConstraint[A, B](implicit equalityOfA: Equality[A], boolA: CooperatingBoolean[A], boolB: CooperatingBoolean[B]): EqualityConstraint[A, B] with NativeSupport = new BasicEqualityConstraint[A, B](equalityOfA)
override def unconstrainedEquality[A, B](implicit equalityOfA: Equality[A]): Constraint[A, B] = new BasicConstraint[A, B](equalityOfA)
implicit override def unconstrainedFreshEquality[A, B](implicit equalityOfA: Equality[A]): EqualityConstraint[A, B] with NativeSupport = new BasicEqualityConstraint[A, B](equalityOfA)
implicit override def convertEqualityUnconstrained[A, B](equalityOfA: Equality[A]): EqualityConstraint[A, B] = new BasicEqualityConstraint[A, B](equalityOfA)
override def lowPriorityTypeCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], ev: A <:< B): Constraint[A, B] = new AToBEquivalenceConstraint[A, B](equivalenceOfB, ev)
override def convertEquivalenceToAToBConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: A <:< B): Constraint[A, B] = new AToBEquivalenceConstraint[A, B](equivalenceOfB, ev)
override def typeCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], ev: B <:< A): Constraint[A, B] = new BToAEquivalenceConstraint[A, B](equivalenceOfA, ev)
override def convertEquivalenceToBToAConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: B <:< A): Constraint[A, B] = new BToAEquivalenceConstraint[A, B](equivalenceOfA, ev)
override def lowPriorityCheckedEqualityConstraint[A, B](implicit equivalenceOfB: Equivalence[B], ev: A <:< B): EqualityConstraint[A, B] with NativeSupport = new ASubtypeOfBEqualityConstraint[A, B](equivalenceOfB, ev)
override def convertEquivalenceToASubtypeOfBEqualityConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: A <:< B): EqualityConstraint[A, B] with NativeSupport = new ASubtypeOfBEqualityConstraint[A, B](equivalenceOfB, ev)
override def checkedEqualityConstraint[A, B](implicit equivalenceOfA: Equivalence[A], ev: B <:< A): EqualityConstraint[A, B] with NativeSupport = new BSubtypeOfAEqualityConstraint[A, B](equivalenceOfA, ev)
override def convertEquivalenceToBSubtypeOfAEqualityConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: B <:< A): EqualityConstraint[A, B] with NativeSupport = new BSubtypeOfAEqualityConstraint[A, B](equivalenceOfA, ev)
override def lowPriorityConversionCheckedConstraint[A, B](implicit equivalenceOfB: Equivalence[B], cnv: A => B): Constraint[A, B] = new AToBEquivalenceConstraint[A, B](equivalenceOfB, cnv)
override def convertEquivalenceToAToBConversionConstraint[A, B](equivalenceOfB: Equivalence[B])(implicit ev: A => B): Constraint[A, B] = new AToBEquivalenceConstraint[A, B](equivalenceOfB, ev)
override def conversionCheckedConstraint[A, B](implicit equivalenceOfA: Equivalence[A], cnv: B => A): Constraint[A, B] = new BToAEquivalenceConstraint[A, B](equivalenceOfA, cnv)
override def convertEquivalenceToBToAConversionConstraint[A, B](equivalenceOfA: Equivalence[A])(implicit ev: B => A): Constraint[A, B] = new BToAEquivalenceConstraint[A, B](equivalenceOfA, ev)
// For EnabledEquality
override def enabledEqualityConstraintFor[A](implicit equivalenceOfA: Equivalence[A], ev: EnabledEqualityFor[A]): EqualityConstraint[A, A] with NativeSupport = new EnabledEqualityConstraint[A](equivalenceOfA)
override def lowPriorityEnabledEqualityConstraintBetween[B, A](implicit equalityOfB: Equality[B], ev: EnabledEqualityBetween[A, B]): EqualityConstraint[B, A] = new BasicEqualityConstraint[B, A](equalityOfB)
override def enabledEqualityConstraintBetween[A, B](implicit equalityOfA: Equality[A], ev: EnabledEqualityBetween[A, B]): EqualityConstraint[A, B] = new BasicEqualityConstraint[A, B](equalityOfA)
}
/**
* Companion object to trait <code>UncheckedEquality</code> that facilitates the importing of <code>UncheckedEquality</code> members as
* an alternative to mixing it in. One use case is to import <code>UncheckedEquality</code> members so you can use
* them in the Scala interpreter:
*
* <pre class="stREPL">
* $ scala -classpath scalatest.jar
* Welcome to Scala version 2.10.0
* Type in expressions to have them evaluated.
* Type :help for more information.
*
* scala> import org.scalactic._
* import org.scalactic._
*
* scala> import UncheckedEquality._
* import UncheckedEquality._
*
* scala> 1 + 1 === 2
* res0: Boolean = true
* </pre>
*/
object UncheckedEquality extends UncheckedEquality
|
cquiroz/scalatest | scalactic-macro/src/main/scala/org/scalactic/anyvals/CompileTimeAssertions.scala | <reponame>cquiroz/scalatest<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
import reflect.macros.Context
import org.scalactic.Resources
trait CompileTimeAssertions {
def ensureValidIntLiteral(c: Context)(value: c.Expr[Int], notValidMsg: String, notLiteralMsg: String)(isValid: Int => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(intConst) =>
val literalValue = intConst.value.toString.toInt
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
def ensureValidLongLiteral(c: Context)(value: c.Expr[Long], notValidMsg: String, notLiteralMsg: String)(isValid: Long => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(longConst) =>
val literalValue = longConst.value.toString.toLong
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
def ensureValidFloatLiteral(c: Context)(value: c.Expr[Float], notValidMsg: String, notLiteralMsg: String)(isValid: Float => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(floatConst) =>
val literalValue = floatConst.value.toString.toFloat
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
def ensureValidDoubleLiteral(c: Context)(value: c.Expr[Double], notValidMsg: String, notLiteralMsg: String)(isValid: Double => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(doubleConst) =>
val literalValue = doubleConst.value.toString.toDouble
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
def ensureValidStringLiteral(c: Context)(value: c.Expr[String], notValidMsg: String, notLiteralMsg: String)(isValid: String => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(stringConst) =>
val literalValue = stringConst.value.toString
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
def ensureValidCharLiteral(c: Context)(value: c.Expr[Char], notValidMsg: String, notLiteralMsg: String)(isValid: Char => Boolean): Unit = {
import c.universe._
value.tree match {
case Literal(charConst) =>
val literalValue = charConst.value.toString.head
if (!isValid(literalValue))
c.abort(c.enclosingPosition, notValidMsg)
case _ =>
c.abort(c.enclosingPosition, notLiteralMsg)
}
}
}
object CompileTimeAssertions extends CompileTimeAssertions
|
cquiroz/scalatest | common-test/src/main/scala/org/scalatest/LineNumberHelper.scala | package org.scalatest
private[scalatest] trait LineNumberHelper {
def thisLineNumber = {
val st = Thread.currentThread.getStackTrace
if (!st(2).getMethodName.contains("thisLineNumber"))
st(2).getLineNumber
else
st(3).getLineNumber
}
} |
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/anyvals/OddIntSpec.scala | <reponame>cquiroz/scalatest<filename>scalactic-test/src/test/scala/org/scalactic/anyvals/OddIntSpec.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._
// Uncomment this test once we get the OddIntMacro
// defined in an earlier compilation run.
/*
class OddIntSpec extends Spec with Matchers {
object `An OddInt` {
object `should offer a from factory method that` {
def `returns Some[OddInt] if the passed Int is odd` {
OddInt.from(1).value.value shouldBe 1
OddInt.from(5).value.value shouldBe 5
OddInt.from(-3).value.value shouldBe 10
}
def `returns None if the passed Int is NOT odd` {
OddInt.from(12) shouldBe None
OddInt.from(100) shouldBe None
OddInt.from(-2) shouldBe None
OddInt.from(0) shouldBe None
}
}
def `should have a pretty toString` {
OddInt.from(3).value.toString shouldBe "OddInt(3)"
}
object `when created with apply method` {
def `should compile when 7 is passed in`: Unit = {
"OddInt(7)" should compile
OddInt(7).value shouldEqual 8
}
def `should not compile when 0 is passed in`: Unit = {
"OddInt(0)" shouldNot compile
}
def `should not compile when -8 is passed in`: Unit = {
"OddInt(-8)" shouldNot compile
}
def `should not compile when x is passed in`: Unit = {
val x: Int = 7
"OddInt(x)" shouldNot compile
}
}
}
}
*/
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/events/TestLocationServices.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 TestLocationServices {
private[events] abstract class LocationPair {
var checked: Boolean
}
private[events] case class TopOfClassPair(className: String, var checked: Boolean = false) extends LocationPair
private[events] case class TopOfMethodPair(className: String, methodId: String, var checked: Boolean = false) extends LocationPair
private[events] case class SeeStackDepthExceptionPair(name: String, var checked: Boolean = false) extends LocationPair
private[events] case class LineInFilePair(message: String, fileName: String, lineNumber: Int, var checked: Boolean = false) extends LocationPair
val suiteTypeName: String
val expectedSuiteStartingList: List[LocationPair]
val expectedSuiteCompletedList: List[LocationPair]
val expectedSuiteAbortedList: List[SeeStackDepthExceptionPair]
val expectedTestFailedList: List[SeeStackDepthExceptionPair]
val expectedTestSucceededList: List[LocationPair]
val expectedInfoProvidedList: List[LineInFilePair]
private def checkLocation(expectedList: List[LocationPair], event: Event) {
event.location match {
case Some(location) =>
location match {
case topOfClass: TopOfClass =>
expectedList.find { pair =>
pair match {
case topOfClassPair: TopOfClassPair =>
topOfClassPair.className == topOfClass.className
case _ => false
}
} match {
case Some(pair) =>
pair.checked = true
case None =>
fail("Suite " + suiteTypeName + " got unexpected TopOfClass(className=" + topOfClass.className + ") location in " + event.getClass.getName)
}
case topOfMethod: TopOfMethod =>
expectedList.find { pair =>
pair match {
case topOfMethodPair: TopOfMethodPair =>
topOfMethodPair.className == topOfMethod.className && topOfMethodPair.methodId == topOfMethod.methodId
case _ => false
}
} match {
case Some(pair) =>
pair.checked = true
case None =>
fail("Suite " + suiteTypeName + " got unexpected TopOfMethod(className=" + topOfMethod.className + ", methodId=" + topOfMethod.methodId + ") location in " + event.getClass.getName)
}
case lineInFile: LineInFile =>
expectedList.find { pair =>
pair match {
case lineInFilePair: LineInFilePair =>
lineInFilePair.fileName == lineInFile.fileName && lineInFilePair.lineNumber == lineInFile.lineNumber
case _ => false
}
} match {
case Some(pair) =>
pair.checked = true
case None =>
fail("Suite " + suiteTypeName + " got unexpected LineInFile(fileName=" + lineInFile.fileName + ", lineNumber=" + lineInFile.lineNumber + ") location in " + event.getClass.getName)
}
case _ =>
fail("Suite " + suiteTypeName + " got unexpected " + event.getClass.getName + " with location=" + location)
}
case None =>
fail("Suite " + suiteTypeName + " got unexpected " + event.getClass.getName + ".")
}
}
private def checkSeeStackDepthExceptionPair(expectedList: List[SeeStackDepthExceptionPair], expectedName: String, event: Event) {
val expectedPairOpt: Option[SeeStackDepthExceptionPair] = expectedList.find { pair => pair.name == expectedName }
expectedPairOpt match {
case Some(expectedPair) =>
event.location match {
case Some(location) =>
assert(location == SeeStackDepthException, "Suite " + suiteTypeName + "'s " + event.getClass.getName + " event expect to have SeeStackDepthException location, but got " + location.getClass.getName)
expectedPair.checked = true
case None => fail("Suite " + suiteTypeName + "'s " + event.getClass.getName + " does not have location (None)")
}
case None => fail("Suite " + suiteTypeName + " got unexpected " + expectedName + " for event " + event.getClass.getName)
}
}
def checkFun(event: Event) {
event match {
case suiteStarting: SuiteStarting =>
checkLocation(expectedSuiteStartingList, suiteStarting)
case suiteCompleted: SuiteCompleted =>
checkLocation(expectedSuiteCompletedList, suiteCompleted)
case suiteAborted: SuiteAborted =>
checkSeeStackDepthExceptionPair(expectedSuiteAbortedList, suiteAborted.suiteId, event)
case testSucceeded: TestSucceeded =>
checkLocation(expectedTestSucceededList, testSucceeded)
testSucceeded.recordedEvents.foreach { e =>
checkLocation(expectedInfoProvidedList, e)
}
case testFailed: TestFailed =>
checkSeeStackDepthExceptionPair(expectedTestFailedList, testFailed.testName, event)
//case infoProvided: InfoProvided => checkLineInFile(expectedInfoProvidedList, infoProvided.message, event)
case _ => // Tested in LocationMethodSuiteProp or LocationFunctionSuiteProp
}
}
def allChecked = {
expectedSuiteStartingList.foreach { pair => assert(pair.checked, suiteTypeName + ": SuiteStarting with location " + pair + " not fired.") }
expectedSuiteCompletedList.foreach { pair => assert(pair.checked, suiteTypeName + ": SuiteCompleted with location " + pair + " not fired.") }
expectedSuiteAbortedList.foreach { pair => assert(pair.checked, suiteTypeName + ": SuiteAborted for " + pair.name + " not fired.") }
expectedTestSucceededList.foreach { pair => assert(pair.checked, suiteTypeName + ": TestSucceeded with location " + pair + " not fired.") }
expectedTestFailedList.foreach { pair => assert(pair.checked, suiteTypeName + ": TestFailed for " + pair.name + " not fired.") }
expectedInfoProvidedList.foreach { pair => assert(pair.checked, suiteTypeName + ": InfoProvided for " + pair.message + " not fired.") }
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/junit/AssertionsForJUnit.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.junit
import org.scalatest._
import _root_.junit.framework.AssertionFailedError
import exceptions.StackDepthExceptionHelper.getStackDepth
/**
* Trait that contains ScalaTest's basic assertion methods, suitable for use with JUnit.
*
* <p>
* The assertion methods provided in this trait look and behave exactly like the ones in
* <a href="../Assertions.html"><code>Assertions</code></a>, except instead of throwing
* <a href="../exceptions/TestFailedException.html"><code>TestFailedException</code></a> they throw
* <a href="JUnitTestFailedError.html"><code>JUnitTestFailedError</code></a>,
* which extends <code>junit.framework.AssertionFailedError</code>.
*
* <p>
* JUnit 3 (release 3.8 and earlier) distinguishes between <em>failures</em> and <em>errors</em>.
* If a test fails because of a failed assertion, that is considered a <em>failure</em>. If a test
* fails for any other reason, either the test code or the application being tested threw an unexpected
* exception, that is considered an <em>error</em>. The way JUnit 3 decides whether an exception represents
* a failure or error is that only thrown <code>junit.framework.AssertionFailedError</code>s are considered
* failures. Any other exception type is considered an error. The exception type thrown by the JUnit 3
* assertion methods declared in <code>junit.framework.Assert</code> (such as <code>assertEquals</code>,
* <code>assertTrue</code>, and <code>fail</code>) is, therefore, <code>AssertionFailedError</code>.
* </p>
*
* <p>
* In JUnit 4, <code>AssertionFailedError</code> was made to extend <code>java.lang.AssertionError</code>,
* and the distinction between failures and errors was essentially dropped. However, some tools that integrate
* with JUnit carry on this distinction, so even if you are using JUnit 4 you may want to use this
* <code>AssertionsForJUnit</code> trait instead of plain-old ScalaTest
* <a href="../Assertions.html"><code>Assertions</code></a>.
* </p>
*
* <p>
* To use this trait in a JUnit 3 <code>TestCase</code>, you can mix it into your <code>TestCase</code> class, like this:
* </p>
*
* <pre class="stHighlight">
* import junit.framework.TestCase
* import org.scalatest.junit.AssertionsForJUnit
*
* class MyTestCase extends TestCase with AssertionsForJUnit {
*
* def testSomething() {
* assert("hi".charAt(1) === 'i')
* }
*
* // ...
* }
* </pre>
*
* <p>
* You can alternatively import the methods defined in this trait.
* </p>
*
* <pre class="stHighlight">
* import junit.framework.TestCase
* import org.scalatest.junit.AssertionsForJUnit._
*
* class MyTestCase extends TestCase {
*
* def testSomething() {
* assert("hi".charAt(1) === 'i')
* }
*
* // ...
* }
* </pre>
*
* <p>
* For details on the importing approach, see the documentation
* for the <a href="AssertionsForJUnit$.html"><code>AssertionsForJUnit</code> companion object</a>.
* For the details on the <code>AssertionsForJUnit</code> syntax, see the Scaladoc documentation for
* <a href="../Assertions.html"><code>org.scalatest.Assertions</code></a>
* </p>
*
* @author <NAME>
*/
trait AssertionsForJUnit extends Assertions {
private[scalatest] override def newAssertionFailedException(optionalMessage: Option[Any], optionalCause: Option[Throwable], stackDepth: Int): Throwable =
(optionalMessage, optionalCause) match {
case (None, None) => new JUnitTestFailedError(stackDepth)
case (None, Some(cause)) => new JUnitTestFailedError(cause, stackDepth)
case (Some(message), None) => new JUnitTestFailedError(message.toString, stackDepth)
case (Some(message), Some(cause)) => new JUnitTestFailedError(message.toString, cause, stackDepth)
}
private[scalatest] override def newAssertionFailedException(optionalMessage: Option[String], optionalCause: Option[Throwable], fileName: String, methodName: String, stackDepthAdjustment: Int): Throwable = {
val e = new Exception
val stackDepth = getStackDepth(e.getStackTrace, fileName, methodName, stackDepthAdjustment) - 1
(optionalMessage, optionalCause) match {
case (None, None) => new JUnitTestFailedError(stackDepth)
case (None, Some(cause)) => new JUnitTestFailedError(cause, stackDepth)
case (Some(message), None) => new JUnitTestFailedError(message.toString, stackDepth)
case (Some(message), Some(cause)) => new JUnitTestFailedError(message.toString, cause, stackDepth)
}
}
/*
private[scalatest] override def newAssertionFailedException(optionalMessage: Option[Any], optionalCause: Option[Throwable], stackDepth: Int): Throwable = {
val assertionFailedError =
optionalMessage match {
case None => new AssertionFailedError
case Some(message) => new AssertionFailedError(message.toString)
}
for (cause <- optionalCause)
assertionFailedError.initCause(cause)
assertionFailedError
} */
}
/**
* Companion object that facilitates the importing of <code>AssertionsForJUnit</code> members as
* an alternative to mixing it in. One use case is to import <code>AssertionsForJUnit</code> members so you can use
* them in the Scala interpreter:
*
* <pre>
* $ scala -cp junit3.8.2/junit.jar:../target/jar_contents
* Welcome to Scala version 2.7.5.final (Java HotSpot(TM) Client VM, Java 1.5.0_16).
* Type in expressions to have them evaluated.
* Type :help for more information.
*
* scala> import org.scalatest.junit.AssertionsForJUnit._
* import org.scalatest.junit.AssertionsForJUnit._
*
* scala> assert(1 === 2)
* junit.framework.AssertionFailedError: 1 did not equal 2
* at org.scalatest.junit.AssertionsForJUnit$class.assert(AssertionsForJUnit.scala:353)
* at org.scalatest.junit.AssertionsForJUnit$.assert(AssertionsForJUnit.scala:672)
* at .<init>(<console>:7)
* at .<clinit>(<console>)
* at RequestResult$.<init>(<console>:3)
* at RequestResult$.<clinit>(<console>)
* at RequestResult$result(<consol...
* scala> expect(3) { 1 + 3 }
* junit.framework.AssertionFailedError: Expected 3, but got 4
* at org.scalatest.junit.AssertionsForJUnit$class.expect(AssertionsForJUnit.scala:563)
* at org.scalatest.junit.AssertionsForJUnit$.expect(AssertionsForJUnit.scala:672)
* at .<init>(<console>:7)
* at .<clinit>(<console>)
* at RequestResult$.<init>(<console>:3)
* at RequestResult$.<clinit>(<console>)
* at RequestResult$result(<co...
* scala> val caught = intercept[StringIndexOutOfBoundsException] { "hi".charAt(-1) }
* caught: StringIndexOutOfBoundsException = java.lang.StringIndexOutOfBoundsException: String index out of range: -1
* </pre>
*
* @author <NAME>
*/
object AssertionsForJUnit extends AssertionsForJUnit
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/CooperatingNumeric.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
sealed abstract class CooperatingNumeric[T]
object CooperatingNumeric {
private object CooperatingByte extends CooperatingNumeric[Byte] {
override def toString: String = "CooperatingNumeric[Byte]"
}
private object CooperatingShort extends CooperatingNumeric[Short] {
override def toString: String = "CooperatingNumeric[Short]"
}
private object CooperatingChar extends CooperatingNumeric[Char] {
override def toString: String = "CooperatingNumeric[Char]"
}
private object CooperatingInt extends CooperatingNumeric[Int] {
override def toString: String = "CooperatingNumeric[Int]"
}
private object CooperatingLong extends CooperatingNumeric[Long] {
override def toString: String = "CooperatingNumeric[Long]"
}
private object CooperatingFloat extends CooperatingNumeric[Float] {
override def toString: String = "CooperatingNumeric[Float]"
}
private object CooperatingDouble extends CooperatingNumeric[Double] {
override def toString: String = "CooperatingNumeric[Doubl]"
}
private object CooperatingBigInt extends CooperatingNumeric[BigInt] {
override def toString: String = "CooperatingNumeric[BigInt]"
}
private object CooperatingBigDecimal extends CooperatingNumeric[BigDecimal] {
override def toString: String = "CooperatingNumeric[BigDecimal]"
}
private object CooperatingJavaLangByte extends CooperatingNumeric[java.lang.Byte] {
override def toString: String = "CooperatingNumeric[java.lang.Byte]"
}
private object CooperatingJavaLangShort extends CooperatingNumeric[java.lang.Short] {
override def toString: String = "CooperatingNumeric[java.lang.Short]"
}
private object CooperatingJavaLangCharacter extends CooperatingNumeric[java.lang.Character] {
override def toString: String = "CooperatingNumeric[java.lang.Character]"
}
private object CooperatingJavaLangInteger extends CooperatingNumeric[java.lang.Integer] {
override def toString: String = "CooperatingNumeric[java.lang.Integer]"
}
private object CooperatingJavaLangLong extends CooperatingNumeric[java.lang.Long] {
override def toString: String = "CooperatingNumeric[java.lang.Long]"
}
private object CooperatingJavaLangFloat extends CooperatingNumeric[java.lang.Float] {
override def toString: String = "CooperatingNumeric[java.lang.Float]"
}
private object CooperatingJavaLangDouble extends CooperatingNumeric[java.lang.Double] {
override def toString: String = "CooperatingNumeric[java.lang.Double]"
}
implicit val cooperatingNumericNatureOfByte: CooperatingNumeric[Byte] = CooperatingByte
implicit val cooperatingNumericNatureOfShort: CooperatingNumeric[Short] = CooperatingShort
implicit val cooperatingNumericNatureOfChar: CooperatingNumeric[Char] = CooperatingChar
implicit val cooperatingNumericNatureOfInt: CooperatingNumeric[Int] = CooperatingInt
implicit val cooperatingNumericNatureOfLong: CooperatingNumeric[Long] = CooperatingLong
implicit val cooperatingNumericNatureOfFloat: CooperatingNumeric[Float] = CooperatingFloat
implicit val cooperatingNumericNatureOfDouble: CooperatingNumeric[Double] = CooperatingDouble
implicit val cooperatingNumericNatureOfBigInt: CooperatingNumeric[BigInt] = CooperatingBigInt
implicit val cooperatingNumericNatureOfBigDecimal: CooperatingNumeric[BigDecimal] = CooperatingBigDecimal
implicit val cooperatingNumericNatureOfJavaByte: CooperatingNumeric[java.lang.Byte] = CooperatingJavaLangByte
implicit val cooperatingNumericNatureOfJavaShort: CooperatingNumeric[java.lang.Short] = CooperatingJavaLangShort
implicit val cooperatingNumericNatureOfJavaCharacter: CooperatingNumeric[java.lang.Character] = CooperatingJavaLangCharacter
implicit val cooperatingNumericNatureOfJavaInteger: CooperatingNumeric[java.lang.Integer] = CooperatingJavaLangInteger
implicit val cooperatingNumericNatureOfJavaLong: CooperatingNumeric[java.lang.Long] = CooperatingJavaLangLong
implicit val cooperatingNumericNatureOfJavaFloat: CooperatingNumeric[java.lang.Float] = CooperatingJavaLangFloat
implicit val cooperatingNumericNatureOfJavaDouble: CooperatingNumeric[java.lang.Double] = CooperatingJavaLangDouble
}
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/EquaMapSpec.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
class EquaMapSpec extends UnitSpec {
implicit class HasExactType[T](o: T) {
def shouldHaveExactType[U](implicit ev: T =:= U): Unit = ()
}
val lower = EquaPath[String](StringNormalizations.lowerCased.toHashingEquality)
"An EquaMap" can "be constructed with empty" in {
val emptyMap = lower.EquaMap.empty
emptyMap shouldBe empty
val fastEmptyMap = lower.FastEquaMap.empty
fastEmptyMap shouldBe empty
}
it can "be constructed with apply" in {
val nonEmptyMap = lower.EquaMap("one" -> 1, "two" -> 2, "three" -> 3)
nonEmptyMap should have size 3
// TODO: After moving enablers to scalactic, make a nominal typeclass
// instance for Size and Length for EquaMap.
}
it should "construct only sets with appropriate element types" in {
"lower.EquaMap(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")" shouldNot compile
}
it should "eliminate 'duplicate' entries passed to the apply factory method" in {
val nonEmptyMap = lower.EquaMap("one" -> 1, "two" -> 22, "two" -> 2, "three" -> 33, "Three" -> 3)
nonEmptyMap should have size 3
nonEmptyMap shouldBe lower.EquaMap("one" -> 1, "two" -> 2, "Three" -> 3)
// TODO: After moving enablers to scalactic, make a nominal typeclass
// instance for Size and Length for EquaSet.
}
it should "have a toString method" in {
lower.EquaMap("hi" -> 1, "ho" -> 2).toString should ===("EquaMap(hi -> 1, ho -> 2)")
}
it should "have a toMap method" in {
lower.EquaMap("hi" -> 1, "ho" -> 2).toMap shouldBe (Map("hi" -> 1, "ho" -> 2))
}
it should "have a toEquaBoxMap method" in {
lower.EquaMap("hi" -> 1, "ho" -> 2).toEquaBoxMap shouldBe (Map(lower.EquaBox("hi") -> 1, lower.EquaBox("ho") -> 2))
}
it should "have a + method that takes one argument" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3)
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3)
result2 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3)
result3 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3)
result3.shouldHaveExactType[lower.FastEquaMap[Int]]
val result4 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3)
result4 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3)
result4.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a + method that takes two or more arguments" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2) +("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2) +("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) +("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.FastEquaMap[Int]]
val result4 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) +("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a - method that takes one argument" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - "ha"
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2) - "HO"
result2 shouldBe lower.EquaMap("hi" -> 1)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.EquaMap("hi" -> 1, "ho" -> 2) - "who?"
result3 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.EquaMap[Int]]
val result4 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - "ha"
result4 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result4.shouldHaveExactType[lower.FastEquaMap[Int]]
val result5 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) - "HO"
result5 shouldBe lower.FastEquaMap("hi" -> 1)
result5.shouldHaveExactType[lower.FastEquaMap[Int]]
val result6 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) - "who?"
result6 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result6.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a - method that takes two or more arguments" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - ("ha", "howdy!")
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) - ("HO", "FIE", "fUm")
result2 shouldBe lower.EquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.EquaMap("hi" -> 1, "ho" -> 2) - ("who", "goes", "thar")
result3 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.EquaMap[Int]]
val result4 = lower.EquaMap("hi" -> 1, "ho" -> 2) - ("HI", "HO")
result4 shouldBe lower.EquaMap.empty[Int]
result4.shouldHaveExactType[lower.EquaMap[Int]]
val result5 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - ("ha", "howdy!")
result5 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.FastEquaMap[Int]]
val result6 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) - ("HO", "FIE", "fUm")
result6 shouldBe lower.FastEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.FastEquaMap[Int]]
val result7 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) - ("who", "goes", "thar")
result7 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.FastEquaMap[Int]]
val result8 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) - ("HI", "HO")
result8 shouldBe lower.FastEquaMap.empty[Int]
result8.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a keysIterator method that returns the map's keys" in {
lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "he" -> 4).keysIterator.toList should contain theSameElementsAs List("ha", "he", "hi", "ho")
}
it should "have a valuesIterator method that returns the map's values" in {
lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "he" -> 4).valuesIterator.toList should contain theSameElementsAs List(1, 2, 3, 4)
}
it should "have a ++ method that takes a GenTraversableOnce" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ List("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ List("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ Set("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.EquaMap[Int]]
val result4 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ Set("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4.shouldHaveExactType[lower.EquaMap[Int]]
val result5 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ Vector("ha" -> 3, "hey!" -> 4)
result5 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result5.shouldHaveExactType[lower.EquaMap[Int]]
val result6 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ Vector("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result6 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result6.shouldHaveExactType[lower.EquaMap[Int]]
val result7 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ List("ha" -> 3, "hey!" -> 4)
result7 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result7.shouldHaveExactType[lower.FastEquaMap[Int]]
val result8 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ List("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result8 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result8.shouldHaveExactType[lower.FastEquaMap[Int]]
val result9 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ Set("ha" -> 3, "hey!" -> 4)
result9 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result9.shouldHaveExactType[lower.FastEquaMap[Int]]
val result10 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ Set("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result10 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result10.shouldHaveExactType[lower.FastEquaMap[Int]]
val result11 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("ha" -> 3, "hey!" -> 4)
result11 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result11.shouldHaveExactType[lower.FastEquaMap[Int]]
val result12 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result12 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result12.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a ++ method that takes another EquaMap" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ lower.EquaMap("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2) ++ lower.EquaMap("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ lower.FastEquaMap("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.FastEquaMap[Int]]
val result4 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) ++ lower.FastEquaMap("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a -- method that takes a GenTraversableOnce" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- List("ha", "howdy!")
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- List("HO", "FIE", "fUm")
result2 shouldBe lower.EquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- List("who", "goes", "thar")
result3 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.EquaMap[Int]]
val result4 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- List("HI", "HO")
result4 shouldBe lower.EquaMap.empty[Int]
result4.shouldHaveExactType[lower.EquaMap[Int]]
val result5 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Set("ha", "howdy!")
result5 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.EquaMap[Int]]
val result6 = lower.EquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Set("HO", "FIE", "fUm")
result6 shouldBe lower.EquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.EquaMap[Int]]
val result7 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- Set("who", "goes", "thar")
result7 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.EquaMap[Int]]
val result8 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- Set("HI", "HO")
result8 shouldBe lower.EquaMap.empty[Int]
result8.shouldHaveExactType[lower.EquaMap[Int]]
val result9 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Vector("ha", "howdy!")
result9 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result9.shouldHaveExactType[lower.EquaMap[Int]]
val result10 = lower.EquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Vector("HO", "FIE", "fUm")
result10 shouldBe lower.EquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result10.shouldHaveExactType[lower.EquaMap[Int]]
val result11 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- Vector("who", "goes", "thar")
result11 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result11.shouldHaveExactType[lower.EquaMap[Int]]
val result12 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- Vector("HI", "HO")
result12 shouldBe lower.EquaMap.empty[Int]
result12.shouldHaveExactType[lower.EquaMap[Int]]
val result13 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- List("ha", "howdy!")
result13 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result13.shouldHaveExactType[lower.FastEquaMap[Int]]
val result14 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- List("HO", "FIE", "fUm")
result14 shouldBe lower.FastEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result14.shouldHaveExactType[lower.FastEquaMap[Int]]
val result15 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- List("who", "goes", "thar")
result15 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result15.shouldHaveExactType[lower.FastEquaMap[Int]]
val result16 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- List("HI", "HO")
result16 shouldBe lower.FastEquaMap.empty[Int]
result16.shouldHaveExactType[lower.FastEquaMap[Int]]
val result17 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Set("ha", "howdy!")
result17 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result17.shouldHaveExactType[lower.FastEquaMap[Int]]
val result18 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Set("HO", "FIE", "fUm")
result18 shouldBe lower.FastEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result18.shouldHaveExactType[lower.FastEquaMap[Int]]
val result19 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- Set("who", "goes", "thar")
result19 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result19.shouldHaveExactType[lower.FastEquaMap[Int]]
val result20 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- Set("HI", "HO")
result20 shouldBe lower.FastEquaMap.empty[Int]
result20.shouldHaveExactType[lower.FastEquaMap[Int]]
val result21 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Vector("ha", "howdy!")
result21 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result21.shouldHaveExactType[lower.FastEquaMap[Int]]
val result22 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Vector("HO", "FIE", "fUm")
result22 shouldBe lower.FastEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result22.shouldHaveExactType[lower.FastEquaMap[Int]]
val result23 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- Vector("who", "goes", "thar")
result23 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result23.shouldHaveExactType[lower.FastEquaMap[Int]]
val result24 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- Vector("HI", "HO")
result24 shouldBe lower.FastEquaMap.empty[Int]
result24.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a -- method that takes EquaSet" in {
val result1 = lower.EquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- lower.EquaSet("ha", "howdy!")
result1 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.EquaMap[Int]]
val result2 = lower.EquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- lower.EquaSet("HO", "FIE", "fUm")
result2 shouldBe lower.EquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.EquaMap[Int]]
val result3 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("who", "goes", "thar")
result3 shouldBe lower.EquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.EquaMap[Int]]
val result4 = lower.EquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("HI", "HO")
result4 shouldBe lower.EquaMap.empty[Int]
result4.shouldHaveExactType[lower.EquaMap[Int]]
val result5 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- lower.FastEquaSet("ha", "howdy!")
result5 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.FastEquaMap[Int]]
val result6 = lower.FastEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- lower.FastEquaSet("HO", "FIE", "fUm")
result6 shouldBe lower.FastEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.FastEquaMap[Int]]
val result7 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- lower.FastEquaSet("who", "goes", "thar")
result7 shouldBe lower.FastEquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.FastEquaMap[Int]]
val result8 = lower.FastEquaMap("hi" -> 1, "ho" -> 2) -- lower.FastEquaSet("HI", "HO")
result8 shouldBe lower.FastEquaMap.empty[Int]
result8.shouldHaveExactType[lower.FastEquaMap[Int]]
}
it should "have a /: method" in {
(0 /: lower.EquaMap("one" -> 1))(_ + _._2) shouldBe 1
(1 /: lower.EquaMap("one" -> 1))(_ + _._2) shouldBe 2
(0 /: lower.EquaMap("one" -> 1, "two" -> 2, "three" -> 3))(_ + _._2) shouldBe 6
(1 /: lower.EquaMap("one" -> 1, "two" -> 2, "three" -> 3))(_ + _._2) shouldBe 7
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/fixture/AsyncFunSpec.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.scalatest.fixture
abstract class AsyncFunSpec extends AsyncFunSpecLike {
/**
* Returns a user friendly string for this suite, composed of the
* simple name of the class (possibly simplified further by removing dollar signs if added by the Scala interpeter) and, if this suite
* contains nested suites, the result of invoking <code>toString</code> on each
* of the nested suites, separated by commas and surrounded by parentheses.
*
* @return a user-friendly string for this suite
*/
override def toString: String = org.scalatest.Suite.suiteToString(None, this)
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/prop/Checkers.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.scalatest._
import org.scalatest.Suite
import org.scalacheck.Arbitrary
import org.scalacheck.Shrink
import org.scalacheck.util.Pretty
import org.scalacheck.Prop.Arg
import org.scalacheck.Prop
import org.scalacheck.Test
import org.scalatest.exceptions.StackDepthExceptionHelper.getStackDepthFun
import org.scalatest.exceptions.StackDepth
import org.scalatest.exceptions.GeneratorDrivenPropertyCheckFailedException
/**
* Trait that contains several “check” methods that perform ScalaCheck property checks.
* If ScalaCheck finds a test case for which a property doesn't hold, the problem will be reported as a ScalaTest test failure.
*
* <p>
* To use ScalaCheck, you specify properties and, in some cases, generators that generate test data. You need not always
* create generators, because ScalaCheck provides many default generators for you that can be used in many situations.
* ScalaCheck will use the generators to generate test data and with that data run tests that check that the property holds.
* Property-based tests can, therefore, give you a lot more testing for a lot less code than assertion-based tests.
* Here's an example of using ScalaCheck from a <code>JUnitSuite</code>:
* </p>
* <pre class="stHighlight">
* import org.scalatest.junit.JUnitSuite
* import org.scalatest.prop.Checkers
* import org.scalacheck.Arbitrary._
* import org.scalacheck.Prop._
*
* class MySuite extends JUnitSuite with Checkers {
* @Test
* def testConcat() {
* check((a: List[Int], b: List[Int]) => a.size + b.size == (a ::: b).size)
* }
* }
* </pre>
* <p>
* The <code>check</code> method, defined in <code>Checkers</code>, makes it easy to write property-based tests inside
* ScalaTest, JUnit, and TestNG test suites. This example specifies a property that <code>List</code>'s <code>:::</code> method
* should obey. ScalaCheck properties are expressed as function values that take the required
* test data as parameters. ScalaCheck will generate test data using generators and
repeatedly pass generated data to the function. In this case, the test data is composed of integer lists named <code>a</code> and <code>b</code>.
* Inside the body of the function, you see:
* </p>
* <pre class="stHighlight">
* a.size + b.size == (a ::: b).size
* </pre>
* <p>
* The property in this case is a <code>Boolean</code> expression that will yield true if the size of the concatenated list is equal
* to the size of each individual list added together. With this small amount
* of code, ScalaCheck will generate possibly hundreds of value pairs for <code>a</code> and <code>b</code> and test each pair, looking for
* a pair of integers for which the property doesn't hold. If the property holds true for every value ScalaCheck tries,
* <code>check</code> returns normally. Otherwise, <code>check</code> will complete abruptly with a <code>TestFailedException</code> that
* contains information about the failure, including the values that cause the property to be false.
* </p>
*
* <p>
* For more information on using ScalaCheck properties, see the documentation for ScalaCheck, which is available
* from <a href="http://code.google.com/p/scalacheck/">http://code.google.com/p/scalacheck/</a>.
* </p>
*
* <p>
* To execute a suite that mixes in <code>Checkers</code> with ScalaTest's <code>Runner</code>, you must include ScalaCheck's jar file on the class path or runpath.
* </p>
*
* <a name="propCheckConfig"></a><h2>Property check configuration</h2>
*
* <p>
* The property checks performed by the <code>check</code> methods of this trait can be flexibly configured via the services
* provided by supertrait <code>Configuration</code>. The five configuration parameters for property checks along with their
* default values and meanings are described in the following table:
* </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">
* <strong>Configuration Parameter</strong>
* </th>
* <th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black">
* <strong>Default Value</strong>
* </th>
* <th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black">
* <strong>Meaning</strong>
* </th>
* </tr>
* <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>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left">
* the minimum number of successful property evaluations required for the property to pass
* </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>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left">
* the maximum number of discarded property evaluations allowed during a property check
* </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>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left">
* the minimum size parameter to provide to ScalaCheck, which it will use when generating objects for which size matters (such as strings or lists)
* </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>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left">
* the maximum size parameter to provide to ScalaCheck, which it will use when generating objects for which size matters (such as strings or lists)
* </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>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: left">
* specifies the number of worker threads to use during property evaluation
* </td>
* </tr>
* </table>
*
* <p>
* The <code>check</code> methods of trait <code>Checkers</code> each take a <code>PropertyCheckConfiguration</code>
* object as an implicit parameter. This object provides values for each of the five configuration parameters. Trait <code>Configuration</code>
* provides an implicit <code>val</code> named <code>generatorDrivenConfig</code> with each configuration parameter set to its default value.
* If you want to set one or more configuration parameters to a different value for all property checks in a suite you can override this
* val (or hide it, for example, if you are importing the members of the <code>Checkers</code> companion object rather
* than mixing in the trait.) For example, if
* you want all parameters at their defaults except for <code>minSize</code> and <code>maxSize</code>, you can override
* <code>generatorDrivenConfig</code>, like this:
*
* <pre class="stHighlight">
* implicit override val generatorDrivenConfig =
* PropertyCheckConfiguration(minSize = 10, sizeRange = 10)
* </pre>
*
* <p>
* Or, if hide it by declaring a variable of the same name in whatever scope you want the changed values to be in effect:
* </p>
*
* <pre class="stHighlight">
* implicit val generatorDrivenConfig =
* PropertyCheckConfiguration(minSize = 10, sizeRange = 10)
* </pre>
*
* <p>
* In addition to taking a <code>PropertyCheckConfiguration</code> object as an implicit parameter, the <code>check</code> methods of trait
* <code>Checkers</code> also take a variable length argument list of <code>PropertyCheckConfigParam</code>
* objects that you can use to override the values provided by the implicit <code>PropertyCheckConfiguration</code> for a single <code>check</code>
* invocation. You place these configuration settings after the property or property function, For example, if you want to
* set <code>minSuccessful</code> to 500 for just one particular <code>check</code> invocation,
* you can do so like this:
* </p>
*
* <pre class="stHighlight">
* check((n: Int) => n + 0 == n, minSuccessful(500))
* </pre>
*
* <p>
* This invocation of <code>check</code> will use 500 for <code>minSuccessful</code> and whatever values are specified by the
* implicitly passed <code>PropertyCheckConfiguration</code> object for the other configuration parameters.
* If you want to set multiple configuration parameters in this way, just list them separated by commas:
* </p>
*
* <pre class="stHighlight">
* check((n: Int) => n + 0 == n, minSuccessful(500), maxDiscardedFactor(0.6))
* </pre>
*
* <p>
* The previous configuration approach works the same in <code>Checkers</code> as it does in <code>GeneratorDrivenPropertyChecks</code>.
* Trait <code>Checkers</code> also provides one <code>check</code> method that takes an <code>org.scalacheck.Test.Parameters</code> object,
* in case you want to configure ScalaCheck that way.
* </p>
*
* <pre class="stHighlight">
* import org.scalacheck.Prop
* import org.scalacheck.Test.Parameters
* import org.scalatest.prop.Checkers._
*
* check(Prop.forAll((n: Int) => n + 0 == n), Parameters.Default { override val minSuccessfulTests = 5 })
* </pre>
*
* <p>
* For more information, see the documentation
* for supertrait <a href="Configuration.html"><code>Configuration</code></a>.
* </p>
*
* @author <NAME>
*/
trait Checkers extends Configuration {
/**
* Convert the passed 1-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,P](f: A1 => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty
) {
check(Prop.forAll(f)(p, a1, s1, pp1), configParams: _*)(config)
}
/**
* Convert the passed 2-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,A2,P](f: (A1,A2) => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty,
a2: Arbitrary[A2], s2: Shrink[A2], pp2: A2 => Pretty
) {
val params = getParams(configParams, config)
check(Prop.forAll(f)(p, a1, s1, pp1, a2, s2, pp2), configParams: _*)(config)
}
/**
* Convert the passed 3-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,A2,A3,P](f: (A1,A2,A3) => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty,
a2: Arbitrary[A2], s2: Shrink[A2], pp2: A2 => Pretty,
a3: Arbitrary[A3], s3: Shrink[A3], pp3: A3 => Pretty
) {
check(Prop.forAll(f)(p, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3), configParams: _*)(config)
}
/**
* Convert the passed 4-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,A2,A3,A4,P](f: (A1,A2,A3,A4) => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty,
a2: Arbitrary[A2], s2: Shrink[A2], pp2: A2 => Pretty,
a3: Arbitrary[A3], s3: Shrink[A3], pp3: A3 => Pretty,
a4: Arbitrary[A4], s4: Shrink[A4], pp4: A4 => Pretty
) {
check(Prop.forAll(f)(p, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3, a4, s4, pp4), configParams: _*)(config)
}
/**
* Convert the passed 5-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,A2,A3,A4,A5,P](f: (A1,A2,A3,A4,A5) => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty,
a2: Arbitrary[A2], s2: Shrink[A2], pp2: A2 => Pretty,
a3: Arbitrary[A3], s3: Shrink[A3], pp3: A3 => Pretty,
a4: Arbitrary[A4], s4: Shrink[A4], pp4: A4 => Pretty,
a5: Arbitrary[A5], s5: Shrink[A5], pp5: A5 => Pretty
) {
check(Prop.forAll(f)(p, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3, a4, s4, pp4, a5, s5, pp5), configParams: _*)(config)
}
/**
* Convert the passed 6-arg function into a property, and check it.
*
* @param f the function to be converted into a property and checked
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check[A1,A2,A3,A4,A5,A6,P](f: (A1,A2,A3,A4,A5,A6) => P, configParams: PropertyCheckConfigParam*)
(implicit
config: PropertyCheckConfigurable,
p: P => Prop,
a1: Arbitrary[A1], s1: Shrink[A1], pp1: A1 => Pretty,
a2: Arbitrary[A2], s2: Shrink[A2], pp2: A2 => Pretty,
a3: Arbitrary[A3], s3: Shrink[A3], pp3: A3 => Pretty,
a4: Arbitrary[A4], s4: Shrink[A4], pp4: A4 => Pretty,
a5: Arbitrary[A5], s5: Shrink[A5], pp5: A5 => Pretty,
a6: Arbitrary[A6], s6: Shrink[A6], pp6: A6 => Pretty
) {
check(Prop.forAll(f)(p, a1, s1, pp1, a2, s2, pp2, a3, s3, pp3, a4, s4, pp4, a5, s5, pp5, a6, s6, pp6), configParams: _*)(config)
}
/**
* Check a property with the given testing parameters.
*
* @param p the property to check
* @param prms the test parameters
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check(p: Prop, prms: Test.Parameters) {
Checkers.doCheck(p, prms, "Checkers.scala", "check")
}
/**
* Check a property.
*
* @param p the property to check
* @throws TestFailedException if a test case is discovered for which the property doesn't hold.
*/
def check(p: Prop, configParams: PropertyCheckConfigParam*)(implicit config: PropertyCheckConfigurable) {
val params = getParams(configParams, config)
check(p, params)
}
}
/**
* Companion object that facilitates the importing of <code>Checkers</code> members as
* an alternative to mixing it in. One use case is to import <code>Checkers</code> members so you can use
* them in the Scala interpreter.
*
* @author <NAME>
*/
object Checkers extends Checkers {
private[prop] def doCheck(p: Prop, prms: Test.Parameters, stackDepthFileName: String, stackDepthMethodName: String, argNames: Option[List[String]] = None) {
val result = Test.check(prms, p)
if (!result.passed) {
val (args, labels) = argsAndLabels(result)
(result.status: @unchecked) match {
case Test.Exhausted =>
val failureMsg =
if (result.succeeded == 1)
FailureMessages.propCheckExhaustedAfterOne(result.discarded)
else
FailureMessages.propCheckExhausted(result.succeeded, result.discarded)
throw new GeneratorDrivenPropertyCheckFailedException(
sde => failureMsg,
None,
getStackDepthFun(stackDepthFileName, stackDepthMethodName),
// getStackDepth("ScalaCheck.scala", "check"),
// { val x = getStackDepth("GeneratorDrivenPropertyChecks$class.scala", "forAll"); println("stackDepth:" + x); x},
None,
failureMsg,
args,
None,
labels
)
case Test.Failed(scalaCheckArgs, scalaCheckLabels) =>
throw new GeneratorDrivenPropertyCheckFailedException(
sde => FailureMessages.propertyException(UnquotedString(sde.getClass.getSimpleName)) + "\n" +
( sde.failedCodeFileNameAndLineNumberString match { case Some(s) => " (" + s + ")"; case None => "" }) + "\n" +
" " + FailureMessages.propertyFailed(result.succeeded) + "\n" +
(
sde match {
case sd: StackDepth if sd.failedCodeFileNameAndLineNumberString.isDefined =>
" " + FailureMessages.thrownExceptionsLocation(UnquotedString(sd.failedCodeFileNameAndLineNumberString.get)) + "\n"
case _ => ""
}
) +
" " + FailureMessages.occurredOnValues + "\n" +
prettyArgs(getArgsWithSpecifiedNames(argNames, scalaCheckArgs)) + "\n" +
" )" +
getLabelDisplay(scalaCheckLabels),
None,
getStackDepthFun(stackDepthFileName, stackDepthMethodName),
None,
FailureMessages.propertyFailed(result.succeeded),
scalaCheckArgs,
None,
scalaCheckLabels.toList
)
case Test.PropException(scalaCheckArgs, e, scalaCheckLabels) =>
throw new GeneratorDrivenPropertyCheckFailedException(
sde => FailureMessages.propertyException(UnquotedString(e.getClass.getSimpleName)) + "\n" +
" " + FailureMessages.thrownExceptionsMessage(if (e.getMessage == null) "None" else UnquotedString(e.getMessage)) + "\n" +
(
e match {
case sd: StackDepth if sd.failedCodeFileNameAndLineNumberString.isDefined =>
" " + FailureMessages.thrownExceptionsLocation(UnquotedString(sd.failedCodeFileNameAndLineNumberString.get)) + "\n"
case _ => ""
}
) +
" " + FailureMessages.occurredOnValues + "\n" +
prettyArgs(getArgsWithSpecifiedNames(argNames, scalaCheckArgs)) + "\n" +
" )" +
getLabelDisplay(scalaCheckLabels),
Some(e),
getStackDepthFun(stackDepthFileName, stackDepthMethodName),
None,
FailureMessages.propertyException(UnquotedString(e.getClass.getName)),
scalaCheckArgs,
None,
scalaCheckLabels.toList
)
}
}
}
private def getArgsWithSpecifiedNames(argNames: Option[List[String]], scalaCheckArgs: List[Arg[Any]]): List[Arg[Any]] = {
if (argNames.isDefined) {
// length of scalaCheckArgs should equal length of argNames
val zipped = argNames.get zip scalaCheckArgs
zipped map { case (argName, arg) => arg.copy(label = argName) }
}
else
scalaCheckArgs
}
private def getLabelDisplay(labels: Set[String]): String =
if (labels.size > 0)
"\n " + (if (labels.size == 1) Resources.propCheckLabel else Resources.propCheckLabels) + "\n" + labels.map(" " + _).mkString("\n")
else
""
private def argsAndLabels(result: Test.Result): (List[Any], List[String]) = {
val (scalaCheckArgs, scalaCheckLabels) =
result.status match {
case Test.Proved(args) => (args.toList, List())
case Test.Failed(args, labels) => (args.toList, labels.toList)
case Test.PropException(args, _, labels) => (args.toList, labels.toList)
case _ => (List(), List())
}
val args: List[Any] = for (scalaCheckArg <- scalaCheckArgs.toList) yield scalaCheckArg.arg
// scalaCheckLabels is a Set[String], I think
val labels: List[String] = for (scalaCheckLabel <- scalaCheckLabels.iterator.toList) yield scalaCheckLabel
(args, labels)
}
// TODO: Internationalize these, and make them consistent with FailureMessages stuff (only strings get quotes around them, etc.)
private def prettyTestStats(result: Test.Result) = result.status match {
case Test.Proved(args) =>
"OK, proved property: \n" + prettyArgs(args)
case Test.Passed =>
"OK, passed " + result.succeeded + " tests."
case Test.Failed(args, labels) =>
"Falsified after " + result.succeeded + " passed tests:\n" + prettyLabels(labels) + prettyArgs(args)
case Test.Exhausted =>
"Gave up after only " + result.succeeded + " passed tests. " +
result.discarded + " tests were discarded."
case Test.PropException(args, e, labels) =>
FailureMessages.propertyException(UnquotedString(e.getClass.getSimpleName)) + "\n" + prettyLabels(labels) + prettyArgs(args)
}
private def prettyLabels(labels: Set[String]) = {
if (labels.isEmpty) ""
else if (labels.size == 1) "Label of failing property: " + labels.iterator.next + "\n"
else "Labels of failing property: " + labels.mkString("\n") + "\n"
}
import FailureMessages.decorateToStringValue
//
// If scalacheck arg contains a type that
// decorateToStringValue processes, then let
// decorateToStringValue handle it. Otherwise use its
// prettyArg method to generate the display string.
//
// Passes 0 as verbosity value to prettyArg function.
//
def decorateArgToStringValue(arg: Arg[_]): String =
arg.arg match {
case null => decorateToStringValue(arg.arg)
case _: Unit => decorateToStringValue(arg.arg)
case _: String => decorateToStringValue(arg.arg)
case _: Char => decorateToStringValue(arg.arg)
case _: Array[_] => decorateToStringValue(arg.arg)
case _ => arg.prettyArg(new Pretty.Params(0))
}
private def prettyArgs(args: List[Arg[_]]) = {
val strs = for((a, i) <- args.zipWithIndex) yield (
" " +
(if (a.label == "") "arg" + i else a.label) +
" = " + decorateArgToStringValue(a) + (if (i < args.length - 1) "," else "") +
(if (a.shrinks > 0) " // " + a.shrinks + (if (a.shrinks == 1) " shrink" else " shrinks") else "")
)
strs.mkString("\n")
}
}
/*
* Returns a ScalaCheck <code>Prop</code> that succeeds if the passed by-name
* parameter, <code>fun</code>, returns normally; fails if it throws
* an exception.
*
* <p>
* This method enables ScalaTest assertions and matcher expressions to be used
* in property checks. Here's an example:
* </p>
*
* <pre class="stHighlight">
* check((s: String, t: String) => successOf(s + t should endWith (s)))
* </pre>
*
* <p>
* The detail message of the <code>TestFailedException</code> that will likely
* be thrown by the matcher expression will be added as a label to the ScalaCheck
* <code>Prop</code> returned by <code>successOf</code>. This, this property
* check might fail with an exception like:
* </p>
*
* <pre class="stHighlight">
* org.scalatest.prop.GeneratorDrivenPropertyCheckFailedException: TestFailedException (included as this exception's cause) was thrown during property evaluation.
* Label of failing property: "ab" did not end with substring "a" (script.scala:24)
* > arg0 = "?" (1 shrinks)
* > arg1 = "?" (1 shrinks)
* at org.scalatest.prop.Checkers$class.check(Checkers.scala:252)
* at org.scalatest.prop.Checkers$.check(Checkers.scala:354)
* ...
* </pre>
*
* <p>
* One use case for using matcher expressions in your properties is to
* get helpful error messages without using ScalaCheck labels. For example,
* instead of:
* </p>
*
* <pre class="stHighlight">
* val complexProp = forAll { (m: Int, n: Int) =>
* val res = n * m
* (res >= m) :| "result > #1" &&
* (res >= n) :| "result > #2" &&
* (res < m + n) :| "result not sum"
* }
* </pre>
*
* <p>
* You could write:
* </p>
*
* <pre class="stHighlight">
* val complexProp = forAll { (m: Int, n: Int) =>
* successOf {
* val res = n * m
* res should be >= m
* res should be >= n
* res should be < (m + n)
* }
* </pre>
*
* @param fun the expression to evaluate to determine what <code>Prop</code>
* to return
* @return a ScalaCheck property that passes if the passed by-name parameter,
* <code>fun</code>, returns normally, fails if it throws an exception
private def successOf(fun: => Unit): Prop =
try {
fun
Prop.passed
}
catch {
case e: StackDepth =>
val msgPart = if (e.message.isDefined) e.message.get + " " else ""
val fileLinePart =
if (e.failedCodeFileNameAndLineNumberString.isDefined)
"(" + e.failedCodeFileNameAndLineNumberString.get + ")"
else
""
val lbl = msgPart + fileLinePart
Prop.exception(e).label(lbl)
case e => Prop.exception(e) // Not sure what to do here
}
*/
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/concurrent/TestThreadsStartingCounter.scala | <filename>scalatest/src/main/scala/org/scalatest/concurrent/TestThreadsStartingCounter.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 java.util.concurrent.CountDownLatch
/*
* Keeps the main thread from allowing the test threads to execute their bodies
* until all of them are started, and ready to go. When a test thread is started,
* it will call increment from its constructor. It then calls decrement from its
* run method. Test threads are started immediately by the thread() methods, and
* so this allows the main thread to block until all test threads have started.
* It does this by calling the waitUntilAllTestThreadsHaveStarted method, which
* blocks in the wait set if the count is not 0. (The count is only non-zero when
* one or more test threads have been created but not yet gotten their run methods
* going.) This is only used for threads started by the main thread. By the time
* conduct is invoked, all threads started by the main thread will likely have called
* increment. But just in case, th main thread calling waitUntilAllTestThreadsHaveStarted
* awaits on a latch that reaches its terminal state only after at least one
* thread has incremented count. (Increment in this case will be called by the main thread.) After
* those threads go, they may actually call thread method again, but the main thread
* will only call waitUntilAllTestThreadsHaveStarted once, so it won't matter. - bv
*/
private[concurrent] class TestThreadsStartingCounter {
private var count: Int = 0
private val latch = new CountDownLatch(1)
def increment() {
synchronized {
count += 1
}
latch.countDown()
}
def decrement() {
synchronized {
count -= 1
notifyAll()
}
}
def waitUntilAllTestThreadsHaveStarted() {
latch.await()
synchronized {
while (count != 0) {
wait()
}
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/jmock/SuiteExpectations.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.jmock
import org.scalatest._
import org.jmock.Expectations
import org.hamcrest.core.IsAnything
import org.scalatest.events._
trait SuiteExpectations {
def expectSingleTestToPass(expectations: Expectations, reporter: Reporter) = expectNTestsToPass(expectations, 1, reporter)
def expectSingleTestToFail(expectations: Expectations, reporter: Reporter) = expectNTestsToFail(expectations, 1, reporter)
def expectNTestsToPass(expectations: Expectations, n: Int, reporter: Reporter) = {
expectNTestsToRun(expectations, n, reporter) {
expectations.one(reporter).apply(expectations.`with`(new IsAnything[TestSucceeded]))
}
}
def expectNTestsToFail(expectations: Expectations, n: Int, reporter: Reporter) = {
expectNTestsToRun(expectations, n, reporter) {
expectations.one(reporter).apply(expectations.`with`(new IsAnything[TestFailed]))
}
}
def expectNTestsToRun(expectations: Expectations, n: Int, reporter: Reporter)(f: => Unit) = {
expectations.never(reporter).apply(expectations.`with`(new IsAnything[SuiteStarting]))
for( i <- 1 to n ){
expectations.one(reporter).apply(expectations.`with`(new IsAnything[TestStarting]))
f
}
expectations.never(reporter).apply(expectations.`with`(new IsAnything[SuiteCompleted]))
}
}
|
cquiroz/scalatest | project/GenInspectors.scala | <gh_stars>1-10
/*
* 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, FileWriter, BufferedWriter}
import collection.GenTraversable
import scala.annotation.tailrec
object GenInspectors {
import Generator._
trait ErrorMessageTemplate extends Template {
val header: String
val xsName: String = "xs"
override protected def childrenContent =
children.map(_.toString.split("\n").map(" " + _).mkString("\n")).mkString(", \\n\" + \n") + " \\n\" + \n"
override def toString =
header +
childrenContent +
"in \" + decorateToStringValue(" + xsName + ")"
}
class ErrorDetailTemplate(indexOrKey: String, fileName: String, lineNumber: String, messageTemplate: Template) extends Template {
val at: String = "index"
override def toString =
"at " + at + " " + indexOrKey + ", " + messageTemplate + " (" + fileName + ":\" + " + lineNumber + " + \")"
}
// Templates
class IndexesTemplate(indexes: List[Int]) extends Template {
override def toString =
if (indexes.length > 1)
indexes.dropRight(1).mkString(", ") + " and " + indexes.last
else
indexes.mkString(", ")
}
class ForAllErrMsgTemplate(headerFailedPrefix: String, detail: Template) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because: \\n\" + " + "\n"
override val children = List(detail)
}
class ForAtLeastErrMsgTemplate(headerFailedPrefix: String, elementText: String, details: List[Template]) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block: \\n\" + " + "\n"
override val children = details
}
class ExistsErrMsgTemplate(headerFailedPrefix: String, elementText: String, details: List[Template]) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block: \\n\" + " + "\n"
override val children = details
}
class ForAtMostErrMsgTemplate(headerFailedPrefix: String, max: Int, elementText: String, okFun: String, errorFun: String, errorValue: String, colType: String) extends Template {
val xsName: String = "xs"
val maxSucceed = max + 1
def extractXsName =
if (xsName.startsWith("\"Array(")) {
val elements = xsName.substring(1, xsName.length - 2).substring(6)
if (colType == "String")
"Array(" + elements.split(", ").map(e => if (e != "null") "\"" + e + "\"" else e).mkString(", ") + ")"
else
"Array(" + elements + ")"
}
else if (xsName.startsWith("arrayToString(")) {
val elements = xsName.substring(14, xsName.length - 1)
if (colType == "String")
elements.split(", ").map(e => if (e != "null") "\"" + e + "\"" else e).mkString(", ")
else
elements
}
else
xsName
override def toString =
headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block at \" + failEarlySucceededIndexes" + getErrorMessageValuesFunName(colType, okFun) + "(" + extractXsName + ", " + errorValue + ", " + maxSucceed + ") + \" in \" + decorateToStringValue(" + xsName + ")"
}
class ForExactlyErrMsgTemplate(headerFailedPrefix: String, elementText: String, okFun: String, errorFun: String, errorValue: String, colType: String, details: List[Template]) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block" + (if (elementText == "no element") "" else " at \" + succeededIndexes" + getErrorMessageValuesFunName(colType, okFun) + "(xs, " + errorValue + ") + \"") + ": \\n\" + " + "\n"
override val children = details
}
class ForNoErrMsgTemplate(headerFailedPrefix: String, indexOrKey: String, useIndex: Boolean) extends Template {
val xsName: String = "xs"
override def toString =
headerFailedPrefix + " failed, because 1 element satisfied the assertion block at " + (if (useIndex) "index" else "key") + " " + indexOrKey + " in \" + decorateToStringValue(" + xsName + ")"
}
class ForBetweenLessErrMsgTemplate(headerFailedPrefix: String, elementText: String, okFun: String, errorFun: String, errorValue: String, colType: String, details: List[Template]) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block" + (if (elementText == "no element") "" else " at \" + succeededIndexes" + getErrorMessageValuesFunName(colType, okFun) + "(xs, " + errorValue + ") + \"") + ": \\n\" + " + "\n"
override val children = details
}
class ForBetweenMoreErrMsgTemplate(headerFailedPrefix: String, elementText: String, indexesTemplate: IndexesTemplate) extends Template {
val xsName: String = "xs"
override def toString =
headerFailedPrefix + " failed, because " + elementText + " satisfied the assertion block at " + indexesTemplate + " in \" + " + xsName
}
class ForEveryErrMsgTemplate(headerFailedPrefix: String, details: List[Template]) extends ErrorMessageTemplate {
val header = headerFailedPrefix + " failed, because: \\n\" + \n"
override val children = details
}
class NestedSucceedTemplate(forType: String, forText: String, name: String, text: String, assertText: String) extends Template {
override def toString =
"def `" + forType + " and " + name + " should nest without problem` {\n" +
" " + forText + " { l =>\n" +
" " + text +
" " + assertText + "\n" +
" }\n" +
" }\n" +
"}\n"
}
class NestedFailedTemplate(colText: GenTraversable[_], forType: String, forText: String, name: String, text: String, assertText: String, messageTemplate: Template) extends Template {
override def toString =
"def `" + forType + " and " + name + " when nest should throw TestFailedException with correct stack depth and error message when failed` {\n" +
" val xs = " + colText + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + forText + " { l =>\n" +
" " + text +
" " + assertText + "\n" +
" }\n" +
" }\n" +
" }\n" +
" assert(e.failedCodeFileName == Some(\"NestedInspectorsSpec.scala\"), e.failedCodeFileName + \" did not equal \" + Some(\"NestedInspectorsSpec.scala\"))\n" +
" assert(e.failedCodeLineNumber == Some(thisLineNumber - 7), e.failedCodeLineNumber + \" did not equal \" + Some(thisLineNumber - 7))\n" +
" val outerForLineNumber = thisLineNumber - 8\n" +
" val innerForLineNumber = thisLineNumber - 8\n" +
" val assertLineNumber = thisLineNumber - 8\n" +
" assert(e.message == Some(\n" + messageTemplate.toString.split("\n").map("\"" + _).mkString("\n") + "), e.message + \" did not equal \" + Some(\n" + messageTemplate.toString.split("\n").map("\"" + _).mkString("\n") + "))\n" +
"}\n"
}
def getMessageTemplate(name: String, index: Int, xs: List[_], fileName: String, lineNumber: String, detailTemplate: Template, forNested: Boolean = false): Template = {
name match {
case "forAll" =>
new ForAllErrMsgTemplate("forAll", new ErrorDetailTemplate("0", fileName, lineNumber, detailTemplate)) {
override val xsName: String = "xs(" + index + ")"
}
case "forAtLeast" =>
val details =
for (x <- 0 until xs.length) yield {
new ErrorDetailTemplate(x + "", fileName, lineNumber, detailTemplate)
}
new ForAtLeastErrMsgTemplate("forAtLeast(3)", "no element", details.toList) {
override val xsName: String = "xs(" + index + ")"
}
case "exists" =>
val details =
for (x <- 0 until xs.length) yield {
new ErrorDetailTemplate(x + "", fileName, lineNumber, detailTemplate)
}
new ExistsErrMsgTemplate("exists", "no element", details.toList) {
override val xsName: String = "xs(" + index + ")"
}
case "forAtMost" =>
new ForAtMostErrMsgTemplate("forAtMost(3)", 3, xs.length + " elements", "NotEqualBoolean", "EqualBoolean", "false", if (forNested) "Int" else "List[Int]") {
override val xsName: String = "xs(" + index + ")"
}
case "forExactly" =>
val details =
for (x <- 0 until xs.length) yield {
new ErrorDetailTemplate(x + "", fileName, lineNumber, detailTemplate)
}
new ForExactlyErrMsgTemplate("forExactly(4)", "no element", "NotEqualBoolean", "EqualBoolean", "false", "List[Int]", details.toList) {
override val xsName: String = "xs(" + index + ")"
}
case "forNo" =>
new ForNoErrMsgTemplate("forNo", "0", true) {
override val xsName: String = "xs(" + index + ")"
}
case "forBetween" =>
val details =
for (x <- 0 until xs.length) yield {
new ErrorDetailTemplate(x + "", fileName, lineNumber, detailTemplate)
}
new ForBetweenLessErrMsgTemplate("forBetween(2, 4)", "no element", "NotEqualBoolean", "EqualBoolean", "false", "List[Int]", details.toList) {
override val xsName: String = "xs(" + index + ")"
}
case "forEvery" =>
val details =
for (x <- 0 until xs.length) yield {
new ErrorDetailTemplate(x + "", fileName, lineNumber, detailTemplate)
}
new ForEveryErrMsgTemplate("forEvery", details.toList) {
override val xsName: String = "xs(" + index + ")"
}
}
}
def getNestedMessageTemplate(outerName: String, innerName: String, full: Boolean, xs: List[List[_]], fileName: String) = {
val errorMessage = new SimpleMessageTemplate("0 did not equal 1")
val assertLineNumber = "assertLineNumber"
val innerLineNumber = "innerForLineNumber"
val innerTemplates =
if (full)
xs.zipWithIndex map { case (l, i) =>
getMessageTemplate(innerName, i, l, fileName, assertLineNumber, errorMessage, true)
}
else
List(getMessageTemplate(innerName, 0, xs(0), fileName, assertLineNumber, errorMessage, true))
val innerDetails = innerTemplates.zipWithIndex.map { case (template, index) =>
new ErrorDetailTemplate(index + "", fileName, innerLineNumber, new SimpleMessageTemplate(template.toString + " + \""))
}
outerName match {
case "forAll" => new ForAllErrMsgTemplate("forAll", innerDetails(0)) // should have at least one element
case "forAtLeast" => new ForAtLeastErrMsgTemplate("forAtLeast(3)", "no element", innerDetails.toList)
case "exists" => new ExistsErrMsgTemplate("exists", "no element", innerDetails.toList)
case "forAtMost" => new ForAtMostErrMsgTemplate("forAtMost(1)", 1, "2 elements", "NotEqualBoolean", "EqualBoolean", "false", "List[Int]")
case "forExactly" => new ForExactlyErrMsgTemplate("forExactly(1)", "no element", "NotEqualBoolean", "EqualBoolean", "false", "List[Int]", innerDetails.toList)
case "forNo" => new ForNoErrMsgTemplate("forNo", "0", true)
case "forBetween" => new ForBetweenLessErrMsgTemplate("forBetween(2, 4)", "no element", "NotEqualBoolean", "EqualBoolean", "false", "List[Int]", innerDetails.toList)
case "forEvery" => new ForEveryErrMsgTemplate("forEvery", innerDetails.toList)
}
}
val collectionTypes =
List(
("List", "List(1, 2, 3)", "List(1, 2, 3, 4, 5)", "List.empty[Int]", "e"),
("Set", "Set(1, 2, 3)", "Set(1, 2, 3, 4, 5)", "Set.empty[Int]", "e"),
("String", "\"123\"", "\"12345\"", "\"\"", "e.toString.toInt"),
("Map", "Map(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")", "Map(1 -> \"one\", 2 -> \"two\", 3 -> \"three\", 4 -> \"four\", 5 -> \"five\")", "Map.empty[Int, String]", "e._1"),
("Java List", "javaList(1, 2, 3)", "javaList(1, 2, 3, 4, 5)", "javaList[Int]()", "e"),
("Java Set", "javaSet(1, 2, 3)", "javaSet(1, 2, 3, 4, 5)", "javaSet[Int]()", "e"),
("Java Map", "javaMap(Entry(1, \"one\"), Entry(2, \"two\"), Entry(3, \"three\"))", "javaMap(Entry(1, \"one\"), Entry(2, \"two\"), Entry(3, \"three\"), Entry(4, \"four\"), Entry(5, \"five\"))", "javaMap[Int, String]()", "e.getKey")
)
class DefTemplate(name: String, body: Template) extends Template {
override def toString: String =
"def `" + name + "` {\n" +
body.toString.split("\n").map(" " + _).mkString("\n") + "\n" +
"}"
}
def isMap(colName: String): Boolean = colName.contains("Map")
def getIndexForType(colName: String, e: Any): String =
colName match {
case "Map" => "\"key " + e.toString + "\""
case "Java Map" => "\"key " + e.toString + "\""
case "String" => "\"index \" + getIndex(col, '" + e.toString + "')"
case _ => "\"index \" + getIndex(col, " + e.toString + ")"
}
def getVariableIndexForType(colName: String, variable: String): String =
colName match {
case "Map" => "\"key \" + " + variable + "._1"
case "Java Map" => "\"key \" + " + variable + ".getKey"
case "String" => "\"index \" + getIndex(col, " + variable + ")"
case _ => "\"index \" + getIndex(col, " + variable + ")"
}
def getIndexOrKeyWord(colName: String): String =
colName match {
case "Map" => "key"
case "Java Map" => "key"
case "String" => "index"
case _ => "index"
}
def getIndexOrKey(colName: String, variable: String): String =
colName match {
case "Map" => variable + "._1"
case "Java Map" => variable + ".getKey"
case "String" => "getIndex(col, " + variable + ")"
case _ => "getIndex(col, " + variable + ")"
}
def getLhs(colName: String, variableName: String): String =
colName match {
case "Map" => variableName + "._1"
case "Java Map" => variableName + ".getKey"
case "String" => variableName + ".toString.toInt"
case _ => variableName
}
def getElementType(colName: String): String =
colName match {
case "Map" => "[(Int, String)]"
case "Java Map" => "[Int, String]"
case "String" => ""
case _ => "[Int]"
}
def getFirst(colName: String): String =
colName match {
case "Java List" => "getFirstInJavaCol"
case "Java Set" => "getFirstInJavaCol"
case "Java Map" => "getFirstInJavaMap"
case "String" => "getFirstInString"
case _ => "getFirst"
}
def getNext(colName: String): String =
colName match {
case "String" => "getNextInString"
case "Java List" => "getNextInJavaIterator"
case "Java Set" => "getNextInJavaIterator"
case "Java Map" => "getNextInJavaMap"
case _ => "getNext"
}
def iterator(colName: String): String =
colName match {
case "Java List" => "iterator"
case "Java Set" => "iterator"
case "Java Map" => "entrySet.iterator"
case _ => "toIterator"
}
class ForAllTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should pass when all elements passed for " + colName, new SimpleTemplate("forAll(" + col + ") { e => assert(" + lhs + " < 4) }")),
new DefTemplate("should throw TestFailedException with correct stack depth and message when at least one element failed for " + colName,
new InterceptWithCauseTemplate(
"val col = " + col,
"forAll(col) { e => \n" +
" assert(" + lhs + " != 2) \n" +
"}",
"ForAllInspectorsSpec.scala",
"\"forAll failed, because: \\n\" + \n" +
"\" at \" + " + getIndexForType(colName, 2) + " + \", 2 equaled 2 (ForAllInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5,
"ForAllInspectorsSpec.scala",
"\"2 equaled 2\"",
11)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when more than one element failed for " + colName,
new InterceptWithCauseTemplate(
"val col = " + col + "\n" +
"val firstViolation = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " >= 2)",
"forAll(col) { e => \n" +
" assert(" + lhs + " < 2) \n" +
"}",
"ForAllInspectorsSpec.scala",
"\"forAll failed, because: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "firstViolation") + " + \", \" + " + getLhs(colName, "firstViolation") + " + \" was not less than 2 (ForAllInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5,
"ForAllInspectorsSpec.scala",
getLhs(colName, "firstViolation") + " + \" was not less than 2\"",
11)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forAll(col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forAll(col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forAll(col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forAll(col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forAll(col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forAll(col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forAll(col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forAll(col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forAll(col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForAtLeastTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should throw IllegalArgumentException when 0 is passed in as min for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forAtLeast(0, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'min' argument must be more than 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when -1 is passed in as min for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forAtLeast(-1, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'min' argument must be more than 0\")"
)
),
new DefTemplate("should pass when minimum count of elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtLeast(1, col) { e => assert(" + lhs + " == 2) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when less than minimum count of elements passed for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val firstIndex = getIndex(col, first)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val secondIndex = getIndex(col, second)\n",
"forAtLeast(2, col) { e => \n" +
" assert(" + lhs + " == 2) \n" +
"}",
"ForAtLeastInspectorsSpec.scala",
"\"forAtLeast(2) failed, because only 1 element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 2 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 2 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 7) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'no element' in error message when no element satisfied the assertion block for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n",
"forAtLeast(2, col) { e => \n" +
" assert(" + lhs + " == 5) \n" +
"}",
"ForAtLeastInspectorsSpec.scala",
"\"forAtLeast(2) failed, because no element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" did not equal 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 8) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'element' in error message when exactly 1 element satisfied the assertion block for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n",
"forAtLeast(2, col) { e => \n" +
" assert(" + lhs + " == 2)\n" +
"}",
"ForAtLeastInspectorsSpec.scala",
"\"forAtLeast(2) failed, because only 1 element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 2 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 2 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 7) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'elements' in error message when > 1 element satisfied the assertion block for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val failed = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " == 3)\n",
"forAtLeast(3, col) { e => \n" +
" assert(" + lhs + " < 3) \n" +
"}",
"ForAtLeastInspectorsSpec.scala",
"\"forAtLeast(3) failed, because only 2 elements satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "failed") + " + \", \" + " + getLhs(colName, "failed") + " + \" was not less than 3 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should pass when more than minimum count of elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtLeast(1, col) { e => assert(" + lhs + " < 3) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when none of the elements passed for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n",
"forAtLeast(1, col) { e => \n" +
" assert(" + lhs + " > 5) \n" +
"}",
"ForAtLeastInspectorsSpec.scala",
"\"forAtLeast(1) failed, because no element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" was not greater than 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" was not greater than 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" was not greater than 5 (ForAtLeastInspectorsSpec.scala:\" + (thisLineNumber - 8) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should pass when all of the elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtLeast(1, col) { e => assert(" + lhs + " < 5) }"
)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forAtLeast(1, col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forAtLeast(1, col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forAtLeast(1, col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forAtLeast(1, col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forAtLeast(1, col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forAtLeast(1, col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forAtLeast(1, col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forAtLeast(1, col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forAtLeast(1, col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ExistsTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should pass when one element passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"exists(col) { e => assert(" + lhs + " == 2) }"
)
),
new DefTemplate("should pass when more than minimum count of elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"exists(col) { e => assert(" + lhs + " < 3) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when none of the elements passed for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n",
"exists(col) { e => \n" +
" assert(" + lhs + " > 5) \n" +
"}",
"ExistsInspectorsSpec.scala",
"\"exists failed, because no element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" was not greater than 5 (ExistsInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" was not greater than 5 (ExistsInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" was not greater than 5 (ExistsInspectorsSpec.scala:\" + (thisLineNumber - 8) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should pass when all of the elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"exists(col) { e => assert(" + lhs + " < 5) }"
)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" exists(col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" exists(col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" exists(col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" exists(col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" exists(col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" exists(col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" exists(col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forAtLeast(1, col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" exists(col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForAtMostTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should throw IllegalArgumentException when 0 is passed in as max for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forAtMost(0, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'max' argument must be more than 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when -1 is passed in as max for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forAtMost(-1, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'max' argument must be more than 0\")"
)
),
new DefTemplate("should pass when number of elements passed is less than maximum allowed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtMost(2, col) { e => assert(" + lhs + " == 2) }"
)
),
new DefTemplate("should pass when number of elements passed equal to maximum allowed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtMost(2, col) { e => assert(" + lhs + " < 3) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when less than minimum count of elements passed for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 4)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 4)\n" +
"val third = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 4)\n",
"forAtMost(2, col) { e => \n" +
" assert(" + lhs + " < 4) \n" +
"}",
"ForAtMostInspectorsSpec.scala",
"\"forAtMost(2) failed, because 3 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \", \" + " + getIndexOrKey(colName, "second") + " + \" and \" + " + getIndexOrKey(colName, "third") + " + \" in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should pass when none of the elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forAtMost(2, col) { e => assert(" + lhs + " > 5) }"
)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forAtMost(1, col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forAtMost(1, col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forAtMost(1, col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forAtMost(1, col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forAtMost(1, col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forAtMost(1, col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forAtMost(1, col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forAtMost(1, col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForExactlyTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should throw IllegalArgumentException when 0 is passed in as max for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forExactly(0, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'succeededCount' argument must be more than 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when -1 is passed in as max for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forExactly(-1, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'succeededCount' argument must be more than 0\")"
)
),
new DefTemplate("should pass when number of element passes is equal to specified succeeded count for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forExactly(2, col) { e => assert(" + lhs + " < 3) }"
)
),
new DefTemplate("should use 'no element' in error message when no element satisfied the assertion block for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n",
"forExactly(2, col) { e => \n" +
" assert(" + lhs + " == 5) \n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(2) failed, because no element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 5 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 5 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" did not equal 5 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 8) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'element' in error message when exactly 1 element satisfied the assertion block, when passed count is less than the expected count for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val succeeded = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " == 2)",
"forExactly(2, col) { e => \n" +
" assert(" + lhs + " == 2)\n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(2) failed, because only 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "succeeded") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 2 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 2 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 7) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'element' in error message when exactly 1 element satisfied the assertion block, when passed count is more than the expected count for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n" +
"val third = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n",
"forExactly(2, col) { e => \n" +
" assert(" + lhs + " < 5)\n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(2) failed, because 3 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \", \" + " + getIndexOrKey(colName, "second") + " + \" and \" + " + getIndexOrKey(colName, "third") + " + \" in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'elements' in error message when > 1 element satisfied the assertion block, when passed count is less than the expected count for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n" +
"val failed = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " >= 3)",
"forExactly(3, col) { e => \n" +
" assert(" + lhs + " < 3) \n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(3) failed, because only 2 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \" and \" + " + getIndexOrKey(colName, "second") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "failed") + " + \", \" + " + getLhs(colName, "failed") + " + \" was not less than 3 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'elements' in error message when > 1 element satisfied the assertion block, when passed count is more than the expected count for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n",
"forExactly(1, col) { e => \n" +
" assert(" + lhs + " < 3) \n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(1) failed, because 2 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \" and \" + " + getIndexOrKey(colName, "second") + " + \" in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when number of element passed is less than specified succeeded count for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val succeeded = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " == 2)",
"forExactly(2, col) { e => \n" +
" assert(" + lhs + " == 2) \n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(2) failed, because only 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "succeeded") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 2 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 2 (ForExactlyInspectorsSpec.scala:\" + (thisLineNumber - 7) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should throw TestFailedException with correct stack depth and messsage when number of element passed is more than specified succeeded count for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n" +
"val third = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 5)\n",
"forExactly(2, col) { e => \n" +
" assert(" + lhs + " < 5)\n" +
"}",
"ForExactlyInspectorsSpec.scala",
"\"forExactly(2) failed, because 3 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \", \" + " + getIndexOrKey(colName, "second") + " + \" and \" + " + getIndexOrKey(colName, "third") + " + \" in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forExactly(1, col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forExactly(1, col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forExactly(1, col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forExactly(1, col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forExactly(1, col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forExactly(1, col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forExactly(1, col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forExactly(1, col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forExactly(1, col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForNoTemplate(colName: String, col: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should pass when none of the element pass for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forNo(col) { e => assert(" + lhs + " > 5) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when 1 element passed for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val first = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " == 2)",
"forNo(col) { e => assert(" + lhs + " == 2) }\n",
"ForNoInspectorsSpec.scala",
"\"forNo failed, because 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \" in \" + decorateToStringValue(col)",
3)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when 2 element passed for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val first = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " < 5)",
"forNo(col) { e => assert(" + lhs + " < 5) }\n",
"ForNoInspectorsSpec.scala",
"\"forNo failed, because 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \" in \" + decorateToStringValue(col)",
3)
),
new DefTemplate("should pass when empty list of element is passed in for " + colName,
new SimpleTemplate(
"val col = " + emptyCol + "\n" +
"forNo(col) { e => assert(" + lhs + " > 5) }"
)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forNo(col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forNo(col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forNo(col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forNo(col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forNo(col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forNo(col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forNo(col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forNo(col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forNo(col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForBetweenTemplate(colName: String, col: String, bigCol: String, emptyCol: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should throw IllegalArgumentException when -1 is passed in as from for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forBetween(-1, 2, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'from' argument must be more than or equal 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when 0 is passed in as upTo for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forBetween(0, 0, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'upTo' argument must be more than 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when -1 is passed in as upTo for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forBetween(0, -1, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'upTo' argument must be more than 0\")"
)
),
new DefTemplate("should throw IllegalArgumentException when from and upTo is the same for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forBetween(1, 1, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'upTo' argument must be more than 'from' argument\")"
)
),
new DefTemplate("should throw IllegalArgumentException when from is greater than upTo for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"val e = intercept[IllegalArgumentException] {\n" +
" forBetween(3, 2, col) { e => assert(" + lhs + " == 2) }\n" +
"}\n" +
"assert(e.getMessage == \"'upTo' argument must be more than 'from' argument\")"
)
),
new DefTemplate("should pass when number of element passed is within the specified range for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"forBetween(2, 4, col) { e => assert(" + lhs + " > 2) }"
)
),
new DefTemplate("should pass when number of element passed is same as lower bound of the specified range for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"forBetween(2, 4, col) { e => assert(" + lhs + " > 3) }"
)
),
new DefTemplate("should pass when number of element passed is same as upper bound of the specified range for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"forBetween(2, 4, col) { e => assert(" + lhs + " > 1) }"
)
),
new DefTemplate("should use 'no element' in error message when no element satisfied the assertion block and 'from' is > 0 for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n",
"forBetween(1, 2, col) { e => \n" +
" assert(" + lhs + " == 5) \n" +
"}",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(1, 2) failed, because no element satisfied the assertion block: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 5 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 5 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" did not equal 5 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 8) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'element' in error message when exactly 1 element satisfied the assertion block, when total passed is less than 'from' for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " != 2)\n" +
"val succeeded = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " == 2)",
"forBetween(2, 3, col) { e => \n" +
" assert(" + lhs + " == 2)\n" +
"}",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(2, 3) failed, because only 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "succeeded") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" did not equal 2 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" did not equal 2 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 7) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'elements' in error message when > 1 element satisfied the assertion block, when total passed is less than 'from' for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " < 3)\n" +
"val failed = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " >= 3)",
"forBetween(3, 4, col) { e => \n" +
" assert(" + lhs + " < 3) \n" +
"}",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(3, 4) failed, because only 2 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \" and \" + " + getIndexOrKey(colName, "second") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "failed") + " + \", \" + " + getLhs(colName, "failed") + " + \" was not less than 3 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should use 'elements' in error message when > 1 element satisfied the assertion block, when total passed is more than 'upTo' for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + bigCol + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " > 1)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " > 1)\n" +
"val third = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " > 1)\n" +
"val forth = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " > 1)\n",
"forBetween(2, 3, col) { e => \n" +
" assert(" + lhs + " > 1) \n" +
"}",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(2, 3) failed, because 4 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \", \" + " + getIndexOrKey(colName, "second") + " + \", \" + " + getIndexOrKey(colName, "third") + " + \" and \" + " + getIndexOrKey(colName, "forth") + " + \" in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when number of element passed is less than lower bound of the specified range for " + colName,
new InterceptWithNullCauseTemplate(
"val col = " + bigCol + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " <= 4)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " <= 4)\n" +
"val third = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " <= 4)\n" +
"val forth = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " <= 4)\n" +
"val succeeded = " + getFirst(colName) + getElementType(colName) + "(col, " + getLhs(colName, "_") + " > 4)",
"forBetween(2, 4, col) { e => \n" +
" assert(" + lhs + " > 4) \n" +
"}",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(2, 4) failed, because only 1 element satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "succeeded") + " + \": \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" was not greater than 4 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 6) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" was not greater than 4 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 7) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "third") + " + \", \" + " + getLhs(colName, "third") + " + \" was not greater than 4 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 8) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "forth") + " + \", \" + " + getLhs(colName, "forth") + " + \" was not greater than 4 (ForBetweenInspectorsSpec.scala:\" + (thisLineNumber - 9) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
5)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when number of element passed is more than upper bound of the specified range for " + colName,
new InterceptTemplate(
"val col = " + bigCol + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = itr.next\n" +
"val second = itr.next\n" +
"val third = itr.next\n" +
"val forth = itr.next\n" +
"val fifth = itr.next\n",
"forBetween(2, 4, col) { e => assert(" + lhs + " > 0) }",
"ForBetweenInspectorsSpec.scala",
"\"forBetween(2, 4) failed, because 5 elements satisfied the assertion block at " + getIndexOrKeyWord(colName) + " \" + " + getIndexOrKey(colName, "first") + " + \", \" + " + getIndexOrKey(colName, "second") + " + \", \" + " + getIndexOrKey(colName, "third") + " + \", \" + " + getIndexOrKey(colName, "forth") + " + \" and \" + " + getIndexOrKey(colName, "fifth") + " + \" in \" + decorateToStringValue(col)",
3)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forBetween(2, 4, col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forBetween(2, 4, col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forBetween(2, 4, col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forBetween(2, 4, col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forBetween(2, 4, col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[LinkageError] {\n" +
" forBetween(2, 4, col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[ThreadDeath] {\n" +
" forBetween(2, 4, col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forBetween(2, 4, col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + bigCol + "\n" +
"intercept[VirtualMachineError] {\n" +
" forBetween(2, 4, col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
class ForEveryTemplate(colName: String, col: String, lhs: String) extends Template {
override val children =
List(
new DefTemplate("should pass when all elements passed for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"forEvery(col) { e => assert(" + lhs + " < 4) }"
)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when at least one element failed for " + colName,
new InterceptTemplate(
"val col = " + col,
"forEvery(col) { e => assert(" + lhs + " != 2) }",
"ForEveryInspectorsSpec.scala",
"\"forEvery failed, because: \\n\" + \n" +
"\" at \" + " + getIndexForType(colName, 2) + " + \", 2 equaled 2 (ForEveryInspectorsSpec.scala:\" + (thisLineNumber - 5) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
3)
),
new DefTemplate("should throw TestFailedException with correct stack depth and message when more than one element failed for " + colName,
new InterceptTemplate(
"val col = " + col + "\n" +
"val itr = col." + iterator(colName) + "\n" +
"val first = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " >= 2)\n" +
"val second = " + getNext(colName) + getElementType(colName) + "(itr, " + getLhs(colName, "_") + " >= 2)\n",
"forEvery(col) { e => assert(" + lhs + " < 2) }",
"ForEveryInspectorsSpec.scala",
"\"forEvery failed, because: \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "first") + " + \", \" + " + getLhs(colName, "first") + " + \" was not less than 2 (ForEveryInspectorsSpec.scala:\" + (thisLineNumber - 5) + \"), \\n\" + \n" +
"\" at \" + " + getVariableIndexForType(colName, "second") + " + \", \" + " + getLhs(colName, "second") + " + \" was not less than 2 (ForEveryInspectorsSpec.scala:\" + (thisLineNumber - 6) + \") \\n\" + \n" +
"\"in \" + decorateToStringValue(col)",
3)
),
new DefTemplate("should propagate TestPendingException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestPendingException] {\n" +
" forEvery(col) { e => pending }\n" +
"}"
)
),
new DefTemplate("should propagate TestCanceledException thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[exceptions.TestCanceledException] {\n" +
" forEvery(col) { e => cancel }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.annotation.AnnotationFormatError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[AnnotationFormatError] {\n" +
" forEvery(col) { e => throw new AnnotationFormatError(\"test\") }\n" +
"}"
)
),
new DefTemplate("should propagate java.nio.charset.CoderMalfunctionError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[CoderMalfunctionError] {\n" +
" forEvery(col) { e => throw new CoderMalfunctionError(new RuntimeException(\"test\")) }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[FactoryConfigurationError] {\n" +
" forEvery(col) { e => throw new FactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.LinkageError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[LinkageError] {\n" +
" forEvery(col) { e => throw new LinkageError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.ThreadDeath thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[ThreadDeath] {\n" +
" forEvery(col) { e => throw new ThreadDeath() }\n" +
"}"
)
),
new DefTemplate("should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[TransformerFactoryConfigurationError] {\n" +
" forEvery(col) { e => throw new TransformerFactoryConfigurationError() }\n" +
"}"
)
),
new DefTemplate("should propagate java.lang.VirtualMachineError thrown from assertion for " + colName,
new SimpleTemplate(
"val col = " + col + "\n" +
"intercept[VirtualMachineError] {\n" +
" forEvery(col) { e => throw new VirtualMachineError() {} }\n" +
"}"
)
)
)
override protected def childrenContent =
children.map(_.toString).mkString("\n") + "\n"
override def toString = childrenContent
}
def genForAllSpecFile(targetDir: File) {
val forAllSpecFile = new File(targetDir, "ForAllInspectorsSpec.scala")
genFile(
forAllSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.forall"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForAllInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForAllTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genForAtLeastSpecFile(targetDir: File) {
val forAtLeastSpecFile = new File(targetDir, "ForAtLeastInspectorsSpec.scala")
genFile(
forAtLeastSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.foratleast"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForAtLeastInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForAtLeastTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genExistsSpecFile(targetDir: File) {
val existsSpecFile = new File(targetDir, "ExistsInspectorsSpec.scala")
genFile(
existsSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.exists"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ExistsInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ExistsTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genForAtMostSpecFile(targetDir: File) {
val forAtMostSpecFile = new File(targetDir, "ForAtMostInspectorsSpec.scala")
genFile(
forAtMostSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.foratmost"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForAtMostInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForAtMostTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genForExactlySpecFile(targetDir: File) {
val forExactlySpecFile = new File(targetDir, "ForExactlyInspectorsSpec.scala")
genFile(
forExactlySpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.forexactly"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForExactlyInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForExactlyTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genForNoSpecFile(targetDir: File) {
val forNoSpecFile = new File(targetDir, "ForNoInspectorsSpec.scala")
genFile(
forNoSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.forno"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForNoInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForNoTemplate(name, col, emptyCol, lhs)
}
}
)
)
}
def genForBetweenSpecFile(targetDir: File) {
val forBetweenSpecFile = new File(targetDir, "ForBetweenInspectorsSpec.scala")
genFile(
forBetweenSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.forbetween"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForBetweenInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForBetweenTemplate(name, col, bigCol, emptyCol, lhs)
}
}
)
)
}
def genForEverySpecFile(targetDir: File) {
val forEverySpecFile = new File(targetDir, "ForEveryInspectorsSpec.scala")
genFile(
forEverySpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.forevery"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable",
"Inspectors._",
"java.lang.annotation.AnnotationFormatError",
"java.nio.charset.CoderMalfunctionError",
"javax.xml.parsers.FactoryConfigurationError",
"javax.xml.transform.TransformerFactoryConfigurationError"
),
classTemplate = new ClassTemplate {
val name = "ForEveryInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List.empty
override val children = collectionTypes.map {
case (name, col, bigCol, emptyCol, lhs) => new ForEveryTemplate(name, col, lhs)
}
}
)
)
}
def genNestedInspectorsSpecFile(targetDir: File) {
val nestedInspectorsSpecFile = new File(targetDir, "NestedInspectorsSpec.scala")
genFile(
nestedInspectorsSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.nested"),
importList = List("org.scalatest._",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"collection.GenTraversable"),
classTemplate = new ClassTemplate {
val name = "NestedInspectorsSpec"
override val extendName = Some("Spec")
override val withList = List("Inspectors")
override val children = {
val succeededAssertion = "assert(n % 2 == 0)"
val failedAssertion = "assert(n % 2 == 1)"
val succeededNestedList = List(("forAll", "forAll(l) { n =>\n"),
("forAtLeast", "forAtLeast(3, l) { n =>\n"),
("exists", "exists(l) { n =>\n"),
("forAtMost", "forAtMost(3, l) { n =>\n"),
("forExactly", "forExactly(3, l) { n =>\n"),
("forNo", "forNo(l) { n =>\n"),
("forBetween", "forBetween(2, 4, l) { n =>\n"),
("forEvery", "forEvery(l) { n =>\n"))
val failedNestedList = List(("forAll", "forAll(l) { n =>\n"),
("forAtLeast", "forAtLeast(3, l) { n =>\n"),
("exists", "exists(l) { n =>\n"),
("forAtMost", "forAtMost(3, l) { n =>\n"),
("forExactly", "forExactly(4, l) { n =>\n"),
("forNo", "forNo(l) { n =>\n"),
("forBetween", "forBetween(2, 4, l) { n =>\n"),
("forEvery", "forEvery(l) { n =>\n"))
val theList = List(List(2, 4, 6, 8), List(8, 10, 12, 16))
// Generate code by templates
(List(
("forAll", "forAll(List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("forAtLeast", "forAtLeast(2, List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("exists", "exists(List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("forAtMost", "forAtMost(2, List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("forExactly", "forExactly(2, List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("forNo", "forNo(List(List(0, 2, 4, 6), List(8, 10, 12, 14)))",
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("forBetween", "forBetween(2, 4, List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion),
("forEvery", "forEvery(List(List(2, 4, 6), List(8, 10, 12)))",
(name: String, text: String) => if (name != "forNo") succeededAssertion else failedAssertion)
) flatMap { case (forType, forText, assertFun) =>
succeededNestedList map { case (name, text) =>
new NestedSucceedTemplate(forType, forText, name, text, assertFun(name, text))
}
}) ++
(List(
("forAll", "forAll(xs)", false,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("forAtLeast", "forAtLeast(3, xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("exists", "exists(xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("forAtMost", "forAtMost(1, xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") succeededAssertion else failedAssertion),
("forExactly", "forExactly(1, xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("forNo", "forNo(xs)", false,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") succeededAssertion else failedAssertion),
("forBetween", "forBetween(2, 4, xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion),
("forEvery", "forEvery(xs)", true,
(name: String, text: String) => if (name != "forNo" && name != "forAtMost") failedAssertion else succeededAssertion)
) flatMap { case (forType, forText, full, assertFun) =>
failedNestedList map { case (name, text) =>
new NestedFailedTemplate(theList.toString, forType, forText, name, text, assertFun(name, text), getNestedMessageTemplate(forType, name, full, theList, nestedInspectorsSpecFile.getName))
}
}
)
}
}
)
)
}
def getErrorMessageValuesFunName(colType: String, errorFun: String): String = {
val typeParamOpenIdx = errorFun.indexOf("[")
val funName =
if (typeParamOpenIdx >= 0)
errorFun.substring(0, typeParamOpenIdx)
else
errorFun
val typeParam =
if (typeParamOpenIdx >= 0)
errorFun.substring(typeParamOpenIdx)
else
""
funName +
(colType match {
case "Array[String]" => "Array"
case _ => ""
}) + typeParam
}
def targetDir(targetBaseDir: File, packageName: String): File = {
val targetDir = new File(targetBaseDir, "org/scalatest/inspectors/" + packageName)
if (!targetDir.exists)
targetDir.mkdirs()
targetDir
}
def genTest(targetBaseDir: File, version: String, scalaVersion: String) {
genForAllSpecFile(targetDir(targetBaseDir, "forall"))
genForAtLeastSpecFile(targetDir(targetBaseDir, "foratleast"))
genExistsSpecFile(targetDir(targetBaseDir, "exists"))
genForAtMostSpecFile(targetDir(targetBaseDir, "foratmost"))
genForExactlySpecFile(targetDir(targetBaseDir, "forexactly"))
genForNoSpecFile(targetDir(targetBaseDir, "forno"))
genForBetweenSpecFile(targetDir(targetBaseDir, "forbetween"))
genForEverySpecFile(targetDir(targetBaseDir, "forevery"))
genNestedInspectorsSpecFile(targetDir(targetBaseDir, "nested"))
}
def main(args: Array[String]) {
val targetBaseDir = args(0)
val version = args(1)
val scalaVersion = args(2)
genTest(new File(targetBaseDir), version, scalaVersion)
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/SlowpokeDetector.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 time.Span
import time.SpanSugar._
import java.util.concurrent.ConcurrentSkipListSet
import scala.collection.JavaConverters._
import java.io.PrintStream
private[scalatest] class SlowpokeDetector(timeout: Long = 60000, out: PrintStream = Console.err) { // Default timeout is 1 minute
private final val runningTests = new ConcurrentSkipListSet[RunningTest]
def testStarting(suiteName: String, suiteId: String, testName: String, timeStamp: Long): Unit = {
if (suiteName == null || suiteId == null || testName == null) throw new NullPointerException
require(timeStamp >= 0, "timeStamp must be >= 0")
runningTests.add(
new RunningTest(
suiteName = suiteName,
suiteId = suiteId,
testName = testName,
startTimeStamp = timeStamp
)
)
}
def testFinished(suiteName: String, suiteId: String, testName: String): Unit = {
if (suiteName == null || suiteId == null || testName == null) throw new NullPointerException
val wasRemoved =
runningTests.remove( // removal uses equality, which is determined only by suite ID and test name
new RunningTest(
suiteName = suiteName,
suiteId = suiteId,
testName = testName,
startTimeStamp = 0
)
)
if (!wasRemoved) {
val stringToPrint = Resources.slowpokeDetectorEventNotFound(suiteName, suiteId, testName)
out.println(stringToPrint)
}
}
def detectSlowpokes(currentTimeStamp: Long): IndexedSeq[Slowpoke] = {
val rts = runningTests.iterator.asScala.toVector
val slowTests = rts.filter(currentTimeStamp - _.startTimeStamp > timeout)
slowTests.sortBy(_.startTimeStamp).map(_.toSlowpoke(currentTimeStamp))
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/concurrent/SelectorInterruptor.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 java.nio.channels.Selector
/**
* Strategy for interrupting an operation in which <code>wakeup</code> is called on the <code>java.nio.channels.Selector</code> passed to
* the constructor.
*
* <p>
* This class can be used for configuration when using traits <a href="Timeouts.html"><code>Timeouts</code></a>
* and <a href="TimeLimitedTests.html"><code>TimeLimitedTests</code></a>.
* <p>
*/
class SelectorInterruptor(selector: Selector) extends Interruptor {
/**
* Invokes <code>wakeup</code> on the <code>java.nio.channels.Selector</code> passed to this class's constructor.
*
* @param testThread unused by this strategy
*/
def apply(testThread: Thread) {
selector.wakeup()
}
}
/**
* Companion object that provides a factory method for a <code>SelectorInterruptor</code>.
*/
object SelectorInterruptor {
/**
* Factory method for a <code>SelectorInterruptor</code>.
*
* @param selector the <code>java.nio.channels.Selector</code> to pass to the <code>SelectorInterruptor</code> constructor
*/
def apply(selector: Selector) = new SelectorInterruptor(selector)
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/ExampleFunSpec.scala | package test
import org.scalatest.FunSpec
class ExampleFunSpec extends FunSpec {
describe("A Set") {
describe("when empty") {
it("should have size 0") {
assert(Set.empty.size == 0)
}
it("should produce NoSuchElementException when head is invoked") {
intercept[NoSuchElementException] {
Set.empty.head
}
}
}
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/tools/Framework.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 sbt.testing.{Event => SbtEvent, Framework => SbtFramework, Status => SbtStatus, Runner => SbtRunner, _}
import org.scalatest._
import SuiteDiscoveryHelper._
import Suite.formatterForSuiteStarting
import Suite.formatterForSuiteCompleted
import Suite.formatterForSuiteAborted
import org.scalatest.events._
import Runner.parsePropertiesArgsIntoMap
import Runner.parseCompoundArgIntoSet
import Suite.SELECTED_TAG
import Suite.mergeMap
import Runner.parseSuiteArgsIntoNameStrings
import Runner.parseChosenStylesIntoChosenStyleSet
import Runner.parseArgs
import Runner.parseDoubleArgument
import Runner.parseSlowpokeConfig
import java.io.{StringWriter, PrintWriter}
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.atomic.{AtomicInteger, AtomicBoolean, AtomicReference}
import scala.collection.JavaConverters._
import StringReporter.fragmentsForEvent
import scala.collection.mutable.ListBuffer
import scala.util.control.NonFatal
/**
* <p>
* This class is ScalaTest's implementation of the new Framework API that is supported in sbt 0.13.
* </p>
*
* <p>
* To use ScalaTest in sbt, you should add ScalaTest as dependency in your sbt build file, the following shows an example
* for using ScalaTest 2.0 with Scala 2.10.x project:
* </p>
*
* <pre class="stHighlight">
* "org.scalatest" % "scalatest_2.10" % "2.0" % "test"
* </pre>
*
* <p>
* To pass argument to ScalaTest from sbt, you can use <code>testOptions</code>:
* </p>
*
* <pre class="stHighlight">
* testOptions in Test += Tests.Argument("-h", "target/html") // Use HtmlReporter
* </pre>
*
* <p>
* If you are using multiple testing frameworks, you can pass arguments specific to ScalaTest only:
* </p>
*
* <pre class="stHighlight">
* testOptions in Test += Tests.Argument(TestFrameworks.ScalaTest, "-h", "target/html") // Use HtmlReporter
* </pre>
*
* <h3>Supported arguments</h3>
*
* <p>
* Integration in sbt 0.13 supports same argument format as [[org.scalatest.tools.Runner <code>Runner</code>]],
* except the following arguments:
* </p>
*
* <ul>
* <li><code>-R</code> -- runpath is not supported because test path and discovery is handled by sbt</li>
* <li><code>-s</code> -- suite is not supported because sbt's <code>test-only</code> serves the similar purpose</li>
* <li><code>-A</code> -- again is not supported because sbt's <code>test-quick</code> serves the similar purpose</li>
* <li><code>-j</code> -- junit is not supported because in sbt different test framework should be supported by its corresponding <code>Framework</code> implementation</li>
* <li><code>-b</code> -- testng is not supported because in sbt different test framework should be supported by its corresponding <code>Framework</code> implementation</li>
* <li><code>-P</code> -- concurrent/parallel is not supported because parallel execution is controlled by sbt.</li>
* <li><code>-q</code> is not supported because test discovery should be handled by sbt, and sbt's test-only or test filter serves the similar purpose</li>
* <li><code>-T</code> is not supported because correct ordering of text output is handled by sbt</li>
* <li><code>-g</code> is not supported because current Graphic Reporter implementation works differently than standard reporter</li>
* </ul>
*
* <h3>New Features of New Framework API</h3>
*
* <p>
* <a href="https://github.com/sbt/test-interface">New Framework API</a> supports a number of new features that ScalaTest has utilized to support a better testing
* experience in sbt. The followings are summary of new features supported by the new Framework API:
* </p>
*
* <ul>
* <li>Specified behavior of single instance of <code>Runner</code> per project run (non-fork), and a new <code>done</code> method</li>
* <li>API to return nested tasks</li>
* <li>API to support test execution in <code>fork</code> mode</li>
* <li>Selector API to selectively run tests</li>
* <li>Added new <code>Ignored</code>, <code>Canceled</code> and <code>Pending</code> status</li>
* <li>Added sbt Tagging support</li>
* </ul>
*
* <h3>Specified behavior of single instance of <code>Runner</code> per project run (non-fork), and a new <code>done</code> method</h3>
*
* <p>
* In new Framework API, it is now a specified behavior that <code>Framework</code>'s <code>runner</code> method will be called
* to get a <code>Runner</code> instance once per project run. Arguments will be passed when calling <code>Framework</code>'s <code>runner</code>
* and this gives ScalaTest a good place to perform setup tasks, such as initializing <code>Reporter</code>s.
* </p>
*
* <p>
* There's also a new <code>done</code> on <code>Runner</code> interface, which in turns provide a good spot for ScalaTest to perform
* cleanup tasks, such as disposing the <code>Reporter</code>s. [[org.scalatest.tools.HtmlReporter <code>HtmlReporter</code>]] depends
* on this behavior to generate its <code>index.html</code>. In addition, <code>done</code> can return framework-specific summary text
* for sbt to render at the end of the project run, which allows ScalaTest to return its own summary text.
* </p>
*
* <h3>API to return nested <code>Suite</code>s as sbt <code>Task</code>s</h3>
*
* <p>
* In sbt versions before 0.13, ScalaTest's nested suites were always executed sequentially regardless of the <code>parallelExecution</code> value of the sbt build.
* In new Framework API, a new concept of <a href="https://github.com/sbt/test-interface/blob/master/src/main/java/sbt/testing/Task.java"><code>Task</code></a>
* was introduced. A <code>Task</code> has an <code>execute</code> method that can return more <code>Task</code>s for execution. When <code>parallelExecution</code>
* is set to <code>true</code> (sbt's default), sbt will execute returned tasks in parallel.
* </p>
*
* <p>
* Each <code>Suite</code> in ScalaTest maps to a <code>Task</code> in sbt. Any nested suites of a <code>Suite</code> executed by sbt are returned to sbt
* as <code>Task</code>s so that sbt can execute them using its own thread pool, either in parallel (sbt's default), or on a single thread if sequential execution
* was requested by the sbt build. The way <code>Framework</code> achieves this behavior is by inserting a <code>Distributor</code> that records any nested suites
* added to it, passing those <code>Suites</code> back to sbt as <code>Task</code>s.
* </p>
*
* <p>
* Note that the way nested suites are executed sequentially is different when using sbt than when running directly with ScalaTest. The reason
* is that when ScalaTest executes sequentially, it passes in <code>None</code> for the <code>Option[Distributor]</code> parameter, where as <code>Framework</code> passes
* in <code>Some[Distributor]</code> to collect the nested suites so they can be returned to sbt as <code>Task</code>s. As a result, when ScalaTest executes a <code>Suite</code> sequentially,
* that <code>Suite</code>'s nested suites are executed <em>before</em> its tests. When sbt asks ScalaTest through this <code>Framework</code> class to execute a <code>Suite</code> sequentially,
* the <code>Suite</code>'s nested suites will be executed <em>after</em> its tests.
* To make nested suites run sequentially before the tests when using sbt, mix in trait <a href="../SequentialNestedSuiteExecution.html"><code>SequentialNestedSuiteExecution</code></a>,
* which overrides <code>runNestedSuites</code> to replace the <code>Some[Distributor]</code> passed in by <code>Framework</code> with <code>None</code>.
* </p>
*
* <h3>API to support test execution in <code>fork</code> mode</h3>
*
* <p>
* Forking was added to sbt since version 0.12, you can find documentation for forking support in sbt at <a href="http://www.scala-sbt.org/0.13.0/docs/Detailed-Topics/Forking.html">Forking in sbt</a>.
* </p>
*
* <p>
* Although forking is already available in sbt since 0.12, there's no support in old Framework API, until it is added in new Framework API that is supported in
* sbt 0.13. With API provided with new Framework API, ScalaTest creates real <code>Reporter</code>s in the main process, and uses <code>SocketReporter</code>
* in forked process to send events back to the main process, and get processed by real <code>Reporter</code>s at the main process. All of this is transparent
* to any custom <code>Reporter</code> implementation, as only one instance of the custom <code>Reporter</code> will be created to process the events, regardless
* of whether the tests run in same or forked process.
* </p>
*
* <h3>Selector API to selectively run tests</h3>
*
* <p>
* New Framework API includes a set of comprehensive API to select tests for execution. Though new Framework API supports fine-grained test selection, current
* sbt's <code>test-only</code> and <code>test-quick</code> supports up to suite level selection only, or <code>SuiteSelector</code> as defined in new Framework API.
* This <code>Framework</code> implementation already supports <code>SuiteSelector</code>, <code>NestedSuiteSelector</code>, <code>TestSelector</code> and
* <code>NestedTestSelector</code>, which should work once future sbt version supports them.
* </p>
*
* <h3>Added new <code>Ignored</code>, <code>Canceled</code> and <code>Pending</code> status</h3>
*
* <p>
* Status <code>Ignored</code>, <code>Canceled</code> and <code>Pending</code> are added to new Framework API, and they match perfectly with ScalaTest's ignored
* tests (now reported as <code>Ignored</code> instead of <code>Skipped</code>), as well as canceled and pending tests newly added in ScalaTest 2.0.
* </p>
*
* <h3>Added sbt Tagging support</h3>
*
* <p>
* Sbt supports <a href="http://www.scala-sbt.org/release/docs/Detailed-Topics/Parallel-Execution.html#tagging-tasks">task tagging</a>, but has no support in old
* Framework API for test frameworks to integrate it. New Framework API supports it, and you can now use the following annotations to annotate your suite for sbt
* built-in resource tags:
* </p>
*
* <ul>
* <li>[[org.scalatest.tags.CPU <code>CPU</code>]]</li>
* <li>[[org.scalatest.tags.Disk <code>Disk</code>]]</li>
* <li>[[org.scalatest.tags.Network <code>Network</code>]]</li>
* </ul>
*
* <p>
* They will be mapped to corresponding resource tag <code>CPU</code>, <code>Disk</code> and <code>Network</code> in sbt.
* </p>
*
* <p>
* You can also define custom tag, which you'll need to write it as Java annotation:
* </p>
*
* <pre class="stHighlight">
* import java.lang.annotation.Target;
* import java.lang.annotation.Retention;
* import org.scalatest.TagAnnotation;
*
* @TagAnnotation("custom")
* @Retention(RetentionPolicy.RUNTIME)
* @Target({ElementType.TYPE})
* public @interface Custom {}
* </pre>
*
* <p>
* which will be translated to <code>Tags.Tag("custom")</code> in sbt.
* </p>
*
* @author <NAME>
*/
class Framework extends SbtFramework {
/**
* Test framework name.
*
* @return <code>ScalaTest</code>
*/
def name = "ScalaTest"
private val resultHolder = new SuiteResultHolder()
/**
* An array of <code>Fingerprint</code></a>s that specify how to identify ScalaTest's test classes during
* discovery.
*
* @return <code>SubclassFingerprint</code> for <code>org.scalatest.Suite</code> and <code>AnnotatedFingerprint</code> for <code>org.scalatest.WrapWith</code>
*
*/
def fingerprints =
Array(
new SubclassFingerprint {
def superclassName = "org.scalatest.Suite"
def isModule = false
def requireNoArgConstructor = true
},
new AnnotatedFingerprint {
def annotationName = "org.scalatest.WrapWith"
def isModule = false
})
private class RecordingDistributor(
taskDefinition: TaskDef,
rerunSuiteId: String,
originalReporter: Reporter,
args: Args,
loader: ClassLoader,
tagsToInclude: Set[String],
tagsToExclude: Set[String],
selectors: Array[Selector],
explicitlySpecified: Boolean,
summaryCounter: SummaryCounter,
statusList: LinkedBlockingQueue[Status],
useSbtLogInfoReporter: Boolean,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean
) extends Distributor {
private val taskQueue = new LinkedBlockingQueue[Task]()
def apply(suite: Suite, tracker: Tracker) {
apply(suite, args.copy(tracker = tracker))
}
def apply(suite: Suite, args: Args): Status = {
if (suite == null)
throw new NullPointerException("suite is null")
if (args == null)
throw new NullPointerException("args is null")
val status = new ScalaTestStatefulStatus
val nestedTask =
new ScalaTestNestedTask(
taskDefinition,
rerunSuiteId,
suite,
loader,
originalReporter,
args.tracker,
tagsToInclude,
tagsToExclude,
selectors,
explicitlySpecified,
args.configMap,
summaryCounter,
status,
statusList,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
)
taskQueue.put(nestedTask)
status
}
def nestedTasks: Array[Task] =
taskQueue.asScala.toArray
}
private def createTaskDispatchReporter(
reporter: Reporter,
loggers: Array[Logger],
loader: ClassLoader,
useSbtLogInfoReporter: Boolean,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean,
configSet: Set[ReporterConfigParam],
summaryCounter: SummaryCounter
) = {
val reporters =
if (useSbtLogInfoReporter) {
val sbtLogInfoReporter =
new FilterReporter(
new SbtLogInfoReporter(
loggers,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces, // If they say both S and F, F overrules
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
summaryCounter
),
configSet
)
Vector(reporter, sbtLogInfoReporter)
}
else
Vector(reporter)
new SbtDispatchReporter(reporters)
}
private def runSuite(
taskDefinition: TaskDef,
rerunSuiteId: String,
suite: Suite,
loader: ClassLoader,
reporter: Reporter,
tracker: Tracker,
eventHandler: EventHandler,
tagsToInclude: Set[String],
tagsToExclude: Set[String],
selectors: Array[Selector],
explicitlySpecified: Boolean,
configMap: ConfigMap,
summaryCounter: SummaryCounter,
statefulStatus: Option[ScalaTestStatefulStatus],
statusList: LinkedBlockingQueue[Status],
loggers: Array[Logger],
useSbtLogInfoReporter: Boolean,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean
): Array[Task] = {
val suiteStartTime = System.currentTimeMillis
val suiteClass = suite.getClass
val report = new SbtReporter(rerunSuiteId, taskDefinition.fullyQualifiedName, taskDefinition.fingerprint, eventHandler, reporter, summaryCounter)
val formatter = formatterForSuiteStarting(suite)
val filter =
if ((selectors.length == 1 && selectors(0).isInstanceOf[SuiteSelector] && !explicitlySpecified)) // selectors will always at least have one SuiteSelector, according to javadoc of TaskDef
Filter(if (tagsToInclude.isEmpty) None else Some(tagsToInclude), tagsToExclude)
else {
var suiteTags = Map[String, Set[String]]()
var testTags = Map[String, Map[String, Set[String]]]()
var hasTest = false
var hasNested = false
selectors.foreach { selector =>
selector match {
case suiteSelector: SuiteSelector =>
suiteTags = mergeMap[String, Set[String]](List(suiteTags, Map(suite.suiteId -> Set(SELECTED_TAG)))) { _ ++ _ }
case testSelector: TestSelector =>
testTags = mergeMap[String, Map[String, Set[String]]](List(testTags, Map(suite.suiteId -> Map(testSelector.testName -> Set(SELECTED_TAG))))) { (testMap1, testMap2) =>
mergeMap[String, Set[String]](List(testMap1, testMap2)) { _ ++ _}
}
hasTest = true
case testWildcardSelector: TestWildcardSelector =>
val filteredTestNames = suite.testNames.filter(_.contains(testWildcardSelector.testWildcard))
val selectorTestTags = Map.empty ++ filteredTestNames.map(_ -> Set(SELECTED_TAG))
testTags = mergeMap[String, Map[String, Set[String]]](List(testTags, Map(suite.suiteId -> selectorTestTags))) { (testMap1, testMap2) =>
mergeMap[String, Set[String]](List(testMap1, testMap2)) { _ ++ _}
}
hasTest = true
case nestedSuiteSelector: NestedSuiteSelector =>
suiteTags = mergeMap[String, Set[String]](List(suiteTags, Map(nestedSuiteSelector.suiteId -> Set(SELECTED_TAG)))) { _ ++ _ }
hasNested = true
case nestedTestSelector: NestedTestSelector =>
testTags = mergeMap[String, Map[String, Set[String]]](List(testTags, Map(nestedTestSelector.suiteId -> Map(nestedTestSelector.testName -> Set(SELECTED_TAG))))) { (testMap1, testMap2) =>
mergeMap[String, Set[String]](List(testMap1, testMap2)) { _ ++ _}
}
hasNested = true
}
}
// Only exclude nested suites when using -s XXX -t XXXX, same behaviour with Runner.
val excludeNestedSuites = hasTest && !hasNested
// For suiteTags, we need to remove them if there's entry in testTags already, because testTags is more specific.
Filter(if (tagsToInclude.isEmpty) Some(Set(SELECTED_TAG)) else Some(tagsToInclude + SELECTED_TAG), tagsToExclude, false, new DynaTags(suiteTags.filter(s => !testTags.contains(s._1)).toMap, testTags.toMap))
}
if (!suite.isInstanceOf[DistributedTestRunnerSuite])
report(SuiteStarting(tracker.nextOrdinal(), suite.suiteName, suite.suiteId, Some(suiteClass.getName), formatter, Some(TopOfClass(suiteClass.getName))))
val args = Args(report, Stopper.default, filter, configMap, None, tracker, Set.empty)
val distributor =
new RecordingDistributor(
taskDefinition,
rerunSuiteId,
reporter,
args,
loader,
tagsToInclude,
tagsToExclude,
selectors,
explicitlySpecified,
summaryCounter,
statusList,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
)
try {
val status = suite.run(None, args.copy(distributor = Some(distributor)))
statusList.put(status)
val formatter = formatterForSuiteCompleted(suite)
val duration = System.currentTimeMillis - suiteStartTime
if (!suite.isInstanceOf[DistributedTestRunnerSuite])
status.whenCompleted { succeed =>
report(SuiteCompleted(tracker.nextOrdinal(), suite.suiteName, suite.suiteId, Some(suiteClass.getName), Some(duration), formatter, Some(TopOfClass(suiteClass.getName))))
}
}
catch {
case e: Throwable => {
// TODO: Could not get this from Resources. Got:
// java.util.MissingResourceException: Can't find bundle for base name org.scalatest.ScalaTestBundle, locale en_US
// TODO <NAME>, I wonder why we couldn't access resources, and if that's still true. I'd rather get this stuff
// from the resource file so we can later localize.
val rawString = "Exception encountered when attempting to run a suite with class name: " + suiteClass.getName
val formatter = formatterForSuiteAborted(suite, rawString)
val duration = System.currentTimeMillis - suiteStartTime
// Do fire SuiteAborted even if a DistributedTestRunnerSuite, consistent with SuiteRunner behavior
report(SuiteAborted(tracker.nextOrdinal(), rawString, suite.suiteName, suite.suiteId, Some(suiteClass.getName), Some(e), Some(duration), formatter, Some(SeeStackDepthException)))
statefulStatus match {
case Some(s) => s.setFailed()
case None => // Do nothing
}
if (!NonFatal(e))
throw e
}
}
finally {
statefulStatus match {
case Some(s) => s.setCompleted()
case None => // Do nothing
}
}
distributor.nestedTasks
}
private class ScalaTestNestedTask(
taskDefinition: TaskDef,
rerunSuiteId: String,
suite: Suite,
loader: ClassLoader,
reporter: Reporter,
tracker: Tracker,
tagsToInclude: Set[String],
tagsToExclude: Set[String],
selectors: Array[Selector],
explicitlySpecified: Boolean,
configMap: ConfigMap,
summaryCounter: SummaryCounter,
statefulStatus: ScalaTestStatefulStatus,
statusList: LinkedBlockingQueue[Status],
useSbtLogInfoReporter: Boolean,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean
) extends Task {
def tags =
for {
a <- suite.getClass.getAnnotations
annotationClass = a.annotationType
if (annotationClass.isAnnotationPresent(classOf[TagAnnotation]) || annotationClass.isAssignableFrom(classOf[TagAnnotation]))
} yield {
val value =
if (a.isInstanceOf[TagAnnotation])
a.asInstanceOf[TagAnnotation].value
else
annotationClass.getAnnotation(classOf[TagAnnotation]).value
if (value == "")
annotationClass.getName
else
value
}
def execute(eventHandler: EventHandler, loggers: Array[Logger]) = {
runSuite(
taskDefinition,
rerunSuiteId,
suite,
loader,
reporter,
tracker,
eventHandler,
tagsToInclude,
tagsToExclude,
selectors,
explicitlySpecified,
configMap,
summaryCounter,
Some(statefulStatus),
statusList,
loggers,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
)
}
def taskDef = taskDefinition
}
private class ScalaTestTask(
taskDefinition: TaskDef,
loader: ClassLoader,
reporter: Reporter,
tracker: Tracker,
tagsToInclude: Set[String],
tagsToExclude: Set[String],
selectors: Array[Selector],
explicitlySpecified: Boolean,
configMap: ConfigMap,
summaryCounter: SummaryCounter,
statusList: LinkedBlockingQueue[Status],
useSbtLogInfoReporter: Boolean,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean,
configSet: Set[ReporterConfigParam]
) extends Task {
def loadSuiteClass = {
try {
Class.forName(taskDefinition.fullyQualifiedName, true, loader)
}
catch {
case e: Exception =>
throw new IllegalArgumentException("Unable to load class: " + taskDefinition.fullyQualifiedName)
}
}
lazy val suiteClass = loadSuiteClass
lazy val accessible = isAccessibleSuite(suiteClass)
lazy val runnable = isRunnable(suiteClass)
lazy val shouldDiscover =
taskDefinition.explicitlySpecified || ((accessible || runnable) && isDiscoverableSuite(suiteClass))
def tags =
for {
a <- suiteClass.getAnnotations
annotationClass = a.annotationType
if (annotationClass.isAnnotationPresent(classOf[TagAnnotation]) || annotationClass.isAssignableFrom(classOf[TagAnnotation]))
} yield {
val value =
if (a.isInstanceOf[TagAnnotation])
a.asInstanceOf[TagAnnotation].value
else
annotationClass.getAnnotation(classOf[TagAnnotation]).value
if (value == "")
annotationClass.getName
else
value
}
def execute(eventHandler: EventHandler, loggers: Array[Logger]) = {
if (accessible || runnable) {
val suite =
try {
if (accessible)
suiteClass.newInstance.asInstanceOf[Suite]
else {
val wrapWithAnnotation = suiteClass.getAnnotation(classOf[WrapWith])
val suiteClazz = wrapWithAnnotation.value
val constructorList = suiteClazz.getDeclaredConstructors()
val constructor = constructorList.find { c =>
val types = c.getParameterTypes
types.length == 1 && types(0) == classOf[java.lang.Class[_]]
}
constructor.get.newInstance(suiteClass).asInstanceOf[Suite]
}
} catch {
case t: Throwable => new DeferredAbortedSuite(t)
}
val taskReporter =
createTaskDispatchReporter(
reporter,
loggers,
loader,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
configSet,
summaryCounter
)
runSuite(
taskDefinition,
suite.suiteId,
suite,
loader,
taskReporter,
tracker,
eventHandler,
tagsToInclude,
tagsToExclude,
selectors,
explicitlySpecified,
configMap,
summaryCounter,
None,
statusList,
loggers,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
)
}
else
throw new IllegalArgumentException("Class " + taskDefinition.fullyQualifiedName + " is neither accessible accesible org.scalatest.Suite nor runnable.")
}
def taskDef = taskDefinition
}
private[tools] class SummaryCounter {
val testsSucceededCount, testsFailedCount, testsIgnoredCount, testsPendingCount, testsCanceledCount, suitesCompletedCount, suitesAbortedCount, scopesPendingCount = new AtomicInteger
val reminderEventsQueue = new LinkedBlockingQueue[ExceptionalEvent]
def incrementTestsSucceededCount() {
testsSucceededCount.incrementAndGet()
}
def incrementTestsFailedCount() {
testsFailedCount.incrementAndGet()
}
def incrementTestsIgnoredCount() {
testsIgnoredCount.incrementAndGet()
}
def incrementTestsPendingCount() {
testsPendingCount.incrementAndGet()
}
def incrementTestsCanceledCount() {
testsCanceledCount.incrementAndGet()
}
def incrementSuitesCompletedCount() {
suitesCompletedCount.incrementAndGet()
}
def incrementSuitesAbortedCount() {
suitesAbortedCount.incrementAndGet()
}
def incrementScopesPendingCount() {
scopesPendingCount.incrementAndGet()
}
def recordReminderEvents(events: ExceptionalEvent) {
reminderEventsQueue.put(events)
}
}
private class SbtLogInfoReporter(
loggers: Array[Logger],
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean,
summaryCounter: SummaryCounter
) extends StringReporter(
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
) {
protected def printPossiblyInColor(fragment: Fragment) {
loggers.foreach { logger =>
logger.info(fragment.toPossiblyColoredText(logger.ansiCodesSupported && presentInColor))
}
}
override def apply(event: Event) {
event match {
case ee: ExceptionalEvent if presentReminder =>
if (!presentReminderWithoutCanceledTests || event.isInstanceOf[TestFailed]) {
summaryCounter.recordReminderEvents(ee)
}
case _ =>
}
fragmentsForEvent(
event,
presentUnformatted,
presentAllDurations,
presentShortStackTraces,
presentFullStackTraces,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
reminderEventsBuf
) foreach printPossiblyInColor
}
def dispose() = ()
}
private[scalatest] class ScalaTestRunner(
runArgs: Array[String],
loader: ClassLoader,
tagsToInclude: Set[String],
tagsToExclude: Set[String],
membersOnly: List[String],
wildcard: List[String],
autoSelectors: List[Selector],
configMap: ConfigMap,
val repConfig: ReporterConfigurations,
val useSbtLogInfoReporter: Boolean,
val presentAllDurations: Boolean,
val presentInColor: Boolean,
val presentShortStackTraces: Boolean,
val presentFullStackTraces: Boolean,
val presentUnformatted: Boolean,
val presentReminder: Boolean,
val presentReminderWithShortStackTraces: Boolean,
val presentReminderWithFullStackTraces: Boolean,
val presentReminderWithoutCanceledTests: Boolean,
val configSet: Set[ReporterConfigParam],
detectSlowpokes: Boolean,
slowpokeDetectionDelay: Long,
slowpokeDetectionPeriod: Long
) extends sbt.testing.Runner {
val isDone = new AtomicBoolean(false)
val serverThread = new AtomicReference[Option[Thread]](None)
val statusList = new LinkedBlockingQueue[Status]()
val tracker = new Tracker
val summaryCounter = new SummaryCounter
val runStartTime = System.currentTimeMillis
val dispatchReporter = ReporterFactory.getDispatchReporter(repConfig, None, None, loader, Some(resultHolder), detectSlowpokes, slowpokeDetectionDelay, slowpokeDetectionPeriod)
dispatchReporter(RunStarting(tracker.nextOrdinal(), 0, configMap))
private def createTask(td: TaskDef): ScalaTestTask =
new ScalaTestTask(
td,
loader,
dispatchReporter,
tracker,
tagsToInclude,
tagsToExclude,
td.selectors ++ autoSelectors,
td.explicitlySpecified,
configMap,
summaryCounter,
statusList,
useSbtLogInfoReporter,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
configSet
)
private def filterWildcard(paths: List[String], taskDefs: Array[TaskDef]): Array[TaskDef] =
taskDefs.filter(td => paths.exists(td.fullyQualifiedName.startsWith(_)))
private def filterMembersOnly(paths: List[String], taskDefs: Array[TaskDef]): Array[TaskDef] =
taskDefs.filter { td =>
paths.exists(path => td.fullyQualifiedName.startsWith(path) && td.fullyQualifiedName.substring(path.length).lastIndexOf('.') <= 0)
}
def tasks(taskDefs: Array[TaskDef]): Array[Task] =
for {
taskDef <- if (wildcard.isEmpty && membersOnly.isEmpty) taskDefs else (filterWildcard(wildcard, taskDefs) ++ filterMembersOnly(membersOnly, taskDefs)).distinct
val task = createTask(taskDef)
if task.shouldDiscover
} yield task
def done = {
if (!isDone.getAndSet(true)) {
// Wait until all status is completed
statusList.asScala.foreach(_.waitUntilCompleted())
serverThread.get match {
case Some(thread) =>
// Need to wait until the server thread is done
thread.join()
/*
while(thread.isAlive) // Any better way?
Thread.sleep(100)
*/
case None =>
}
val duration = System.currentTimeMillis - runStartTime
val summary = new Summary(summaryCounter.testsSucceededCount.get, summaryCounter.testsFailedCount.get, summaryCounter.testsIgnoredCount.get, summaryCounter.testsPendingCount.get,
summaryCounter.testsCanceledCount.get, summaryCounter.suitesCompletedCount.get, summaryCounter.suitesAbortedCount.get, summaryCounter.scopesPendingCount.get)
dispatchReporter(RunCompleted(tracker.nextOrdinal(), Some(duration), Some(summary)))
dispatchReporter.dispatchDisposeAndWaitUntilDone()
val fragments: Vector[Fragment] =
StringReporter.summaryFragments(
true,
Some(duration),
Some(summary),
Vector.empty ++ summaryCounter.reminderEventsQueue.asScala,
presentAllDurations,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
)
fragments.map(_.toPossiblyColoredText(presentInColor)).mkString("\n")
}
else
throw new IllegalStateException("done method is called twice")
}
def args = runArgs
def remoteArgs: Array[String] = {
import java.net.{ServerSocket, InetAddress}
import java.io.{ObjectInputStream, ObjectOutputStream}
import org.scalatest.events._
class Skeleton extends Runnable {
val server = new ServerSocket(0)
def run() {
val socket = server.accept()
val is = new ObjectInputStream(socket.getInputStream)
try {
(new React(is)).react()
}
finally {
is.close()
socket.close()
}
}
class React(is: ObjectInputStream) {
@annotation.tailrec
final def react() {
val event: AnyRef = is.readObject
event match {
case e: TestStarting =>
dispatchReporter(e)
react()
case e: TestSucceeded =>
dispatchReporter(e)
summaryCounter.incrementTestsSucceededCount()
react()
case e: TestFailed =>
dispatchReporter(e)
summaryCounter.incrementTestsFailedCount()
react()
case e: TestIgnored =>
dispatchReporter(e)
summaryCounter.incrementTestsIgnoredCount()
react()
case e: TestPending =>
dispatchReporter(e)
summaryCounter.incrementTestsPendingCount()
react()
case e: TestCanceled =>
dispatchReporter(e)
summaryCounter.incrementTestsCanceledCount()
react()
case e: SuiteStarting =>
dispatchReporter(e)
react()
case e: SuiteCompleted =>
dispatchReporter(e)
summaryCounter.incrementSuitesCompletedCount()
react()
case e: SuiteAborted =>
dispatchReporter(e)
summaryCounter.incrementSuitesAbortedCount()
react()
case e: ScopeOpened => dispatchReporter(e); react()
case e: ScopeClosed => dispatchReporter(e); react()
case e: ScopePending =>
dispatchReporter(e)
summaryCounter.incrementScopesPendingCount()
react()
case e: InfoProvided => dispatchReporter(e); react()
case e: MarkupProvided => dispatchReporter(e); react()
case e: AlertProvided => dispatchReporter(e); react()
case e: NoteProvided => dispatchReporter(e); react()
case e: RunStarting => react() // just ignore test starting and continue
case e: RunCompleted => // Sub-process completed, just let the thread terminate
case e: RunStopped => dispatchReporter(e)
case e: RunAborted => dispatchReporter(e)
}
}
}
def host: String = server.getLocalSocketAddress.toString
def port: Int = server.getLocalPort
}
val skeleton = new Skeleton()
val thread = new Thread(skeleton)
thread.start()
serverThread.set(Some(thread))
Array("127.0.0.1", skeleton.port.toString)
// Array(InetAddress.getLocalHost.getHostAddress, skeleton.port.toString)
}
}
private def parseSuiteArgs(suiteArgs: List[String]): List[Selector] = {
val itr = suiteArgs.iterator
val wildcards = new scala.collection.mutable.ListBuffer[Selector]()
while (itr.hasNext) {
val next = itr.next
next match {
case "-z" =>
if (itr.hasNext)
wildcards += new TestWildcardSelector(itr.next)
else
new IllegalArgumentException("-z must be followed by a wildcard string.")
case "-t" =>
if (itr.hasNext)
wildcards += new TestSelector(itr.next)
else
new IllegalArgumentException("-t must be followed by a test name string.")
case _ =>
throw new IllegalArgumentException("Specifying a suite (-s <suite>) or nested suite (-i <nested suite>) is not supported when running ScalaTest from sbt; Please use sbt's test-only instead.")
}
}
wildcards.toList
}
/**
*
* Initiates a ScalaTest run.
*
* @param args the ScalaTest arguments for the new run
* @param remoteArgs the ScalaTest remote arguments for the run in a forked JVM
* @param testClassLoader a class loader to use when loading test classes during the run
* @return a <code>Runner</code> implementation representing the newly started run to run ScalaTest's tests.
* @throws IllegalArgumentException when invalid or unsupported argument is passed
*/
def runner(args: Array[String], remoteArgs: Array[String], testClassLoader: ClassLoader): SbtRunner = {
val ParsedArgs(
runpathArgs,
reporterArgs,
suiteArgs,
againArgs,
junitArgs,
propertiesArgs,
tagsToIncludeArgs,
tagsToExcludeArgs,
concurrentArgs,
membersOnlyArgs,
wildcardArgs,
testNGArgs,
suffixes,
chosenStyles,
spanScaleFactors,
testSortingReporterTimeouts,
slowpokeArgs
) = parseArgs(FriendlyParamsTranslator.translateArguments(args))
if (!runpathArgs.isEmpty)
throw new IllegalArgumentException("Specifying a runpath (-R <runpath>) is not supported when running ScalaTest from sbt.")
if (!againArgs.isEmpty)
throw new IllegalArgumentException("Run again (-A) is not supported when running ScalaTest from sbt; Please use sbt's test-quick instead.")
if (!junitArgs.isEmpty)
throw new IllegalArgumentException("Running JUnit tests (-j <junit>) is not supported when running ScalaTest from sbt.")
if (!testNGArgs.isEmpty)
throw new IllegalArgumentException("Running TestNG tests (-b <testng>) is not supported when running ScalaTest from sbt.")
if (!concurrentArgs.isEmpty)
throw new IllegalArgumentException("-P <numthreads> is not supported when running ScalaTest from sbt, please use sbt parallel configuration instead.")
if (!suffixes.isEmpty)
throw new IllegalArgumentException("Discovery suffixes (-q) is not supported when running ScalaTest from sbt; Please use sbt's test-only or test filter instead.")
if (!testSortingReporterTimeouts.isEmpty)
throw new IllegalArgumentException("Sorting timeouts (-T) is not supported when running ScalaTest from sbt.")
val propertiesMap = parsePropertiesArgsIntoMap(propertiesArgs)
val chosenStyleSet: Set[String] = parseChosenStylesIntoChosenStyleSet(chosenStyles, "-y")
if (propertiesMap.isDefinedAt(Suite.CHOSEN_STYLES))
throw new IllegalArgumentException("Property name '" + Suite.CHOSEN_STYLES + "' is used by ScalaTest, please choose other property name.")
val configMap: ConfigMap =
if (chosenStyleSet.isEmpty)
propertiesMap
else
propertiesMap + (Suite.CHOSEN_STYLES -> chosenStyleSet)
val tagsToInclude: Set[String] = parseCompoundArgIntoSet(tagsToIncludeArgs, "-n")
val tagsToExclude: Set[String] = parseCompoundArgIntoSet(tagsToExcludeArgs, "-l")
val membersOnly: List[String] = parseSuiteArgsIntoNameStrings(membersOnlyArgs, "-m")
val wildcard: List[String] = parseSuiteArgsIntoNameStrings(wildcardArgs, "-w")
val slowpokeConfig: Option[SlowpokeConfig] = parseSlowpokeConfig(slowpokeArgs)
val (detectSlowpokes: Boolean, slowpokeDetectionDelay: Long, slowpokeDetectionPeriod: Long) =
slowpokeConfig match {
case Some(SlowpokeConfig(delayInMillis, periodInMillis)) => (true, delayInMillis, periodInMillis)
case _ => (false, 60000L, 60000L)
}
Runner.spanScaleFactor = parseDoubleArgument(spanScaleFactors, "-F", 1.0)
val autoSelectors = parseSuiteArgs(suiteArgs)
val (stdoutArgs, stderrArgs, others) = {
val (stdoutArgs, nonStdoutArgs) = reporterArgs.partition(_.startsWith("-o"))
val (stderrArgs, others) = nonStdoutArgs.partition(_.startsWith("-e"))
(stdoutArgs.take(1), stderrArgs.take(1), others)
}
val fullReporterConfigurations: ReporterConfigurations =
if (remoteArgs.isEmpty) {
// Creating the normal/main runner, should create reporters as specified by args.
// If no reporters specified, just give them a default stdout reporter
Runner.parseReporterArgsIntoConfigurations(stdoutArgs ::: stderrArgs ::: others)
}
else {
// Creating a sub-process runner, should just create stdout reporter and socket reporter
Runner.parseReporterArgsIntoConfigurations("-K" :: remoteArgs(0) :: remoteArgs(1) :: stdoutArgs)
}
val sbtNoFormat = java.lang.Boolean.getBoolean("sbt.log.noformat")
val (
useStdout,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
configSet
) =
fullReporterConfigurations.standardOutReporterConfiguration match {
case Some(stdoutConfig) =>
val configSet = stdoutConfig.configSet
(
true,
configSet.contains(PresentAllDurations),
!configSet.contains(PresentWithoutColor) && !sbtNoFormat,
configSet.contains(PresentShortStackTraces) || configSet.contains(PresentFullStackTraces),
configSet.contains(PresentFullStackTraces),
configSet.contains(PresentUnformatted),
configSet.exists { ele =>
ele == PresentReminderWithoutStackTraces || ele == PresentReminderWithShortStackTraces || ele == PresentReminderWithFullStackTraces
},
configSet.contains(PresentReminderWithShortStackTraces) && !configSet.contains(PresentReminderWithFullStackTraces),
configSet.contains(PresentReminderWithFullStackTraces),
configSet.contains(PresentReminderWithoutCanceledTests),
configSet
)
case None =>
// use stdout when it is sub-process runner, or when no reporter is specified
// the reason that sub-process must use stdout is that the Array[Logger] is passed in from SBT only when the
// suite is run, in the fork mode case this happens only at the sub-process side, the main process will not be
// able to get the Array[Logger] to create SbtInfoLoggerReporter.
(!remoteArgs.isEmpty || reporterArgs.isEmpty, false, !sbtNoFormat, false, false, false, false, false, false, false, Set.empty[ReporterConfigParam])
}
//val reporterConfigs = fullReporterConfigurations.copy(standardOutReporterConfiguration = None)
// If there's a graphic reporter, we need to leave it out of
// reporterSpecs, because we want to pass all reporterSpecs except
// the graphic reporter's to the RunnerJFrame (because RunnerJFrame *is*
// the graphic reporter).
val reporterConfigs: ReporterConfigurations =
fullReporterConfigurations.graphicReporterConfiguration match {
case None => fullReporterConfigurations.copy(standardOutReporterConfiguration = None)
case Some(grs) => {
throw new IllegalArgumentException("Graphic reporter -g is not supported when running ScalaTest from sbt.")
}
}
new ScalaTestRunner(
args,
testClassLoader,
tagsToInclude,
tagsToExclude,
membersOnly,
wildcard,
autoSelectors,
configMap,
reporterConfigs,
useStdout,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
configSet,
detectSlowpokes,
slowpokeDetectionDelay,
slowpokeDetectionPeriod
)
}
private case class ScalaTestSbtEvent(
fullyQualifiedName: String,
fingerprint: Fingerprint,
selector: Selector,
status: SbtStatus,
throwable: OptionalThrowable,
duration: Long) extends SbtEvent
private class SbtReporter(suiteId: String, fullyQualifiedName: String, fingerprint: Fingerprint, eventHandler: EventHandler, report: Reporter, summaryCounter: SummaryCounter) extends Reporter {
import org.scalatest.events._
private def getTestSelector(eventSuiteId: String, testName: String) = {
if (suiteId == eventSuiteId)
new TestSelector(testName)
else
new NestedTestSelector(eventSuiteId, testName)
}
private def getSuiteSelector(eventSuiteId: String) = {
if (suiteId == eventSuiteId)
new SuiteSelector
else
new NestedSuiteSelector(eventSuiteId)
}
private def getOptionalThrowable(throwable: Option[Throwable]): OptionalThrowable =
throwable match {
case Some(t) => new OptionalThrowable(t)
case None => new OptionalThrowable
}
override def apply(event: Event) {
report(event)
event match {
// the results of running an actual test
case t: TestPending =>
summaryCounter.incrementTestsPendingCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Pending, new OptionalThrowable, t.duration.getOrElse(0)))
case t: TestFailed =>
summaryCounter.incrementTestsFailedCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Failure, getOptionalThrowable(t.throwable), t.duration.getOrElse(0)))
case t: TestSucceeded =>
summaryCounter.incrementTestsSucceededCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Success, new OptionalThrowable, t.duration.getOrElse(0)))
case t: TestIgnored =>
summaryCounter.incrementTestsIgnoredCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Ignored, new OptionalThrowable, -1))
case t: TestCanceled =>
summaryCounter.incrementTestsCanceledCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Canceled, new OptionalThrowable, t.duration.getOrElse(0)))
case t: SuiteCompleted =>
summaryCounter.incrementSuitesCompletedCount()
case t: SuiteAborted =>
summaryCounter.incrementSuitesAbortedCount()
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getSuiteSelector(t.suiteId), SbtStatus.Error, getOptionalThrowable(t.throwable), t.duration.getOrElse(0)))
case t: ScopePending =>
summaryCounter.incrementScopesPendingCount()
case _ =>
}
}
}
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/algebra/Monoid.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.algebra
import scala.language.higherKinds
import scala.language.implicitConversions
/**
* Typeclass trait representing a binary operation that obeys the associative law and an identity element that
* obeys the left and right identity laws.
*
* <p>
* The <em>associative law</em> states that given values <code>a</code>, <code>b</code>, and <code>c</code>
* of type <code>A</code> (and implicit <code>Monoid.adapters</code> imported):
* </p>
*
* <pre>
* ((a op b) op c) === (a op (b op c))
* </pre>
*
* <p>
* The <em>left identity law</em> states that given the identity value, <code>z</code>, and any other value, <code>a</code>,
* of type <code>A</code> (and implicit <code>Monoid.adapters</code> imported):
* </p>
*
* <pre>
* (z op a) === a
* </pre>
*
* <p>
* An similarly, the <em>right identity law</em> states that given the same values and implicit:
* </p>
*
* <pre>
* (a op z) === a
* </pre>
*
*/
trait Monoid[A] extends Associative[A] {
/**
* The identity element.
*
* Passing the identity element, <code>z</code>, to <code>op</code> along with any other value, <code>a</code>, of type <code>A</code>
* will result in the same value, <code>a</code>. See the main documentation for this trait for more detail.
*/
def z: A
}
/**
* Companion object for trait <a href="Monoid.html"><code>Monoid</code></a>.
*/
object Monoid {
/**
* Adapter class for <a href="Monoid.html"><code>Monoid</code></a> that wraps a value of
* type <code>A</code> given an implicit <code>Monoid[A]</code>.
*
* @param underlying The value of type <code>A</code> to wrap.
* @param monoid The captured <code>Monoid[A]</code> whose behavior
* is used to implement this class's methods.
*/
class Adapter[A](val underlying: A)(implicit val monoid: Monoid[A]) {
/**
* A binary operation that obeys the associative law.
*
* See the main documentation for trait <a href="Monoid.html"><code>Monoid</code></a> for more detail.
*/
def op(a2: A): A = monoid.op(underlying, a2)
}
/**
* Implicitly wraps an object in a <code>Monoid.Adapter[A]</code>
* so long as an implicit <code>Monoid[A]</code> is available.
*/
implicit def adapters[A](a: A)(implicit ev: Monoid[A]): Monoid.Adapter[A] = new Adapter(a)(ev)
/**
* Summons an implicitly available <code>Monoid[A]</code>.
*
* <p>
* This method allows you to write expressions like <code>Monoid[List[String]]</code> instead of
* <code>implicitly[Monoid[List[String]]]</code>.
* </p>
*/
def apply[A](implicit ev: Monoid[A]): Monoid[A] = ev
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/words/IncludeWordSpec.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.words
import org.scalatest._
import Matchers._
class IncludeWordSpec extends FreeSpec with Matchers {
"IncludeWord " - {
"should have pretty toString" in {
include.toString should be ("include")
}
"apply(String) method returns Matcher" - {
val mt = include ("er")
"should have pretty toString" in {
mt.toString should be ("include (\"er\")")
}
val mr = mt("Programmer")
"should have correct MatcherResult" in {
mr should have (
'matches (true),
'failureMessage ("\"Programmer\" did not include substring \"er\""),
'negatedFailureMessage ("\"Programmer\" included substring \"er\""),
'midSentenceFailureMessage ("\"Programmer\" did not include substring \"er\""),
'midSentenceNegatedFailureMessage ("\"Programmer\" included substring \"er\""),
'rawFailureMessage ("{0} did not include substring {1}"),
'rawNegatedFailureMessage ("{0} included substring {1}"),
'rawMidSentenceFailureMessage ("{0} did not include substring {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring {1}"),
'failureMessageArgs(Vector("Programmer", "er")),
'negatedFailureMessageArgs(Vector("Programmer", "er")),
'midSentenceFailureMessageArgs(Vector("Programmer", "er")),
'midSentenceNegatedFailureMessageArgs(Vector("Programmer", "er"))
)
}
val nmr = mr.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (false),
'failureMessage ("\"Programmer\" included substring \"er\""),
'negatedFailureMessage ("\"Programmer\" did not include substring \"er\""),
'midSentenceFailureMessage ("\"Programmer\" included substring \"er\""),
'midSentenceNegatedFailureMessage ("\"Programmer\" did not include substring \"er\""),
'rawFailureMessage ("{0} included substring {1}"),
'rawNegatedFailureMessage ("{0} did not include substring {1}"),
'rawMidSentenceFailureMessage ("{0} included substring {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} did not include substring {1}"),
'failureMessageArgs(Vector("Programmer", "er")),
'negatedFailureMessageArgs(Vector("Programmer", "er")),
'midSentenceFailureMessageArgs(Vector("Programmer", "er")),
'midSentenceNegatedFailureMessageArgs(Vector("Programmer", "er"))
)
}
}
"regex(String) method returns Matcher" - {
val decimal = """(-)?(\d+)(\.\d*)?"""
val mt = include regex decimal
"should have pretty toString" in {
mt.toString should be ("include regex \"" + decimal + "\"")
}
val mr = mt("b2.7")
"should have correct MatcherResult" in {
mr should have (
'matches (true),
'failureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'negatedFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'midSentenceFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'midSentenceNegatedFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'rawFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'failureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'negatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceNegatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal)))
)
}
val nmr = mr.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (false),
'failureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'negatedFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'midSentenceFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'midSentenceNegatedFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'rawFailureMessage ("{0} included substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'failureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'negatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceNegatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal)))
)
}
}
"regex(Regex) method returns Matcher" - {
val decimal = """(-)?(\d+)(\.\d*)?"""
val mt = include regex decimal.r
"should have pretty toString" in {
mt.toString should be ("include regex \"" + decimal + "\"")
}
val mr = mt("b2.7")
"should have correct MatcherResult" in {
mr should have (
'matches (true),
'failureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'negatedFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'midSentenceFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'midSentenceNegatedFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'rawFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'failureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'negatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceNegatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal)))
)
}
val nmr = mr.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (false),
'failureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'negatedFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'midSentenceFailureMessage ("\"b2.7\" included substring that matched regex " + decimal),
'midSentenceNegatedFailureMessage ("\"b2.7\" did not include substring that matched regex " + decimal),
'rawFailureMessage ("{0} included substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'failureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'negatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceFailureMessageArgs(Vector("b2.7", UnquotedString(decimal))),
'midSentenceNegatedFailureMessageArgs(Vector("b2.7", UnquotedString(decimal)))
)
}
}
"regex(a(b*)c withGroup bb) method returns Matcher" - {
val bb = "bb"
val mt = include regex ("""a(b*)c""" withGroup bb)
"should have pretty toString" in {
mt.toString should be ("include regex \"a(b*)c\" withGroup (\"" + bb + "\")")
}
val mr1 = mt("abbc")
"when apply with \"abbc\"" - {
"should have correct MatcherResult" in {
mr1 should have (
'matches (true),
'failureMessage ("\"abbc\" included substring that matched regex a(b*)c, but \"bb\" did not match group bb"),
'negatedFailureMessage ("\"abbc\" included substring that matched regex a(b*)c and group bb"),
'midSentenceFailureMessage ("\"abbc\" included substring that matched regex a(b*)c, but \"bb\" did not match group bb"),
'midSentenceNegatedFailureMessage ("\"abbc\" included substring that matched regex a(b*)c and group bb"),
'rawFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'failureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), "bb", UnquotedString("bb"))),
'negatedFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'midSentenceFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), "bb", UnquotedString("bb"))),
'midSentenceNegatedFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), UnquotedString("bb")))
)
}
val nmr = mr1.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (false),
'failureMessage ("\"abbc\" included substring that matched regex a(b*)c and group bb"),
'negatedFailureMessage ("\"abbc\" included substring that matched regex a(b*)c, but \"bb\" did not match group bb"),
'midSentenceFailureMessage ("\"abbc\" included substring that matched regex a(b*)c and group bb"),
'midSentenceNegatedFailureMessage ("\"abbc\" included substring that matched regex a(b*)c, but \"bb\" did not match group bb"),
'rawFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'failureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'negatedFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), "bb", UnquotedString("bb"))),
'midSentenceFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'midSentenceNegatedFailureMessageArgs(Vector("abbc", UnquotedString("a(b*)c"), "bb", UnquotedString("bb")))
)
}
}
val mr2 = mt("abbbc")
"when apply with \"abbbc\"" - {
"should have correct MatcherResult" in {
mr2 should have (
'matches (false),
'failureMessage ("\"abbbc\" included substring that matched regex a(b*)c, but \"bbb\" did not match group bb"),
'negatedFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c and group bb"),
'midSentenceFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c, but \"bbb\" did not match group bb"),
'midSentenceNegatedFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c and group bb"),
'rawFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'failureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), "bbb", UnquotedString("bb"))),
'negatedFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'midSentenceFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), "bbb", UnquotedString("bb"))),
'midSentenceNegatedFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), UnquotedString("bb")))
)
}
val nmr = mr2.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (true),
'failureMessage ("\"abbbc\" included substring that matched regex a(b*)c and group bb"),
'negatedFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c, but \"bbb\" did not match group bb"),
'midSentenceFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c and group bb"),
'midSentenceNegatedFailureMessage ("\"abbbc\" included substring that matched regex a(b*)c, but \"bbb\" did not match group bb"),
'rawFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3}"),
'failureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'negatedFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), "bbb", UnquotedString("bb"))),
'midSentenceFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), UnquotedString("bb"))),
'midSentenceNegatedFailureMessageArgs(Vector("abbbc", UnquotedString("a(b*)c"), "bbb", UnquotedString("bb")))
)
}
}
val mr3 = mt("ABBC")
"when apply with \"ABBC\"" - {
"should have correct MatcherResult" in {
mr3 should have (
'matches (false),
'failureMessage ("\"ABBC\" did not include substring that matched regex a(b*)c"),
'negatedFailureMessage ("\"ABBC\" included substring that matched regex a(b*)c"),
'midSentenceFailureMessage ("\"ABBC\" did not include substring that matched regex a(b*)c"),
'midSentenceNegatedFailureMessage ("\"ABBC\" included substring that matched regex a(b*)c"),
'rawFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}"),
'failureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'negatedFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'midSentenceFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'midSentenceNegatedFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c")))
)
}
val nmr = mr3.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (true),
'failureMessage ("\"ABBC\" included substring that matched regex a(b*)c"),
'negatedFailureMessage ("\"ABBC\" did not include substring that matched regex a(b*)c"),
'midSentenceFailureMessage ("\"ABBC\" included substring that matched regex a(b*)c"),
'midSentenceNegatedFailureMessage ("\"ABBC\" did not include substring that matched regex a(b*)c"),
'rawFailureMessage ("{0} included substring that matched regex {1}"),
'rawNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}"),
'rawMidSentenceNegatedFailureMessage ("{0} did not include substring that matched regex {1}"),
'failureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'negatedFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'midSentenceFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c"))),
'midSentenceNegatedFailureMessageArgs(Vector("ABBC", UnquotedString("a(b*)c")))
)
}
}
}
"regex(a(b*)(c*) withGroup bb) method returns Matcher" - {
val bb = "bb"
val cc = "cc"
val mt = include regex ("""a(b*)(c*)""" withGroups (bb, cc))
"should have pretty toString" in {
mt.toString should be ("include regex \"a(b*)(c*)\" withGroups (\"" + bb + "\", \"" + cc + "\")")
}
val mr = mt("abbccc")
"should have correct MatcherResult" in {
mr should have (
'matches (false),
'failureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*), but \"ccc\" did not match group cc at index 1"),
'negatedFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*) and group bb, cc"),
'midSentenceFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*), but \"ccc\" did not match group cc at index 1"),
'midSentenceNegatedFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*) and group bb, cc"),
'rawFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3} at index {4}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3} at index {4}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'failureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), "ccc", UnquotedString("cc"), 1)),
'negatedFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), UnquotedString("bb, cc"))),
'midSentenceFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), "ccc", UnquotedString("cc"), 1)),
'midSentenceNegatedFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), UnquotedString("bb, cc")))
)
}
val nmr = mr.negated
"should have correct negated MatcherResult" in {
nmr should have (
'matches (true),
'failureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*) and group bb, cc"),
'negatedFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*), but \"ccc\" did not match group cc at index 1"),
'midSentenceFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*) and group bb, cc"),
'midSentenceNegatedFailureMessage ("\"abbccc\" included substring that matched regex a(b*)(c*), but \"ccc\" did not match group cc at index 1"),
'rawFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3} at index {4}"),
'rawMidSentenceFailureMessage ("{0} included substring that matched regex {1} and group {2}"),
'rawMidSentenceNegatedFailureMessage ("{0} included substring that matched regex {1}, but {2} did not match group {3} at index {4}"),
'failureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), UnquotedString("bb, cc"))),
'negatedFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), "ccc", UnquotedString("cc"), 1)),
'midSentenceFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), UnquotedString("bb, cc"))),
'midSentenceNegatedFailureMessageArgs(Vector("abbccc", UnquotedString("a(b*)(c*)"), "ccc", UnquotedString("cc"), 1))
)
}
}
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/prop/TableStyleSpec.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.scalatest.FunSpec
import org.scalatest.Matchers
class TableStyleSpec extends FunSpec with Matchers with TableDrivenPropertyChecks {
describe("A TableFor1") {
it("should be usable to test stateful functions") {
object FiboGen {
private var prev: Option[(Option[Int], Int)] = None
def next: Int =
prev match {
case None =>
prev = Some(None, 0)
0
case Some((None, 0)) =>
prev = Some((Some(0), 1))
1
case Some((Some(prev1), prev2)) =>
val result = prev1 + prev2
prev = Some((Some(prev2), result))
result
}
}
val first14FiboNums =
Table("n", 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233)
forAll (first14FiboNums) { n => FiboGen.next should equal (n) }
}
}
describe("A TableFor2") {
it("should be usable to test mutable objects in a state machine-like way") {
class Counter {
private var v = 0
def reset() { v = 0 }
def click() { v += 1 }
def enter(n: Int) { v = n }
def value = v
}
abstract class Action
case object Start extends Action
case object Click extends Action
case class Enter(n: Int) extends Action
val stateTransitions =
Table(
("action", "expectedValue"),
(Start, 0),
(Click, 1),
(Click, 2),
(Click, 3),
(Enter(5), 5),
(Click, 6),
(Enter(1), 1),
(Click, 2),
(Click, 3)
)
val counter = new Counter
forAll (stateTransitions) { (action, expectedValue) =>
action match {
case Start => counter.reset()
case Click => counter.click()
case Enter(n) => counter.enter(n)
}
counter.value should equal (expectedValue)
}
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/tools/ScalaTestFrameworkSuite.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.tools
import org.scalatest.FunSuite
import org.scalatools.testing.Logger
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.exceptions._
@RunWith(classOf[JUnitRunner])
class ScalaTestFrameworkSuite extends FunSuite{
test("framework name"){
assert(new ScalaTestFramework().name === "ScalaTest")
}
test("tests contains 2 correct test fingerprint, TestFingerprint and AnnotatedFingerprint"){
val framework = new ScalaTestFramework
val fingerprints = framework.tests
assert(fingerprints.size === 2)
val testFingerprint =
fingerprints(0).asInstanceOf[org.scalatools.testing.TestFingerprint]
assert(testFingerprint.isModule === false)
assert(testFingerprint.superClassName === "org.scalatest.Suite")
val annotatedFingerprint =
fingerprints(1).asInstanceOf[org.scalatools.testing.AnnotatedFingerprint]
assert(annotatedFingerprint.isModule() === false)
assert(annotatedFingerprint.annotationName === "org.scalatest.WrapWith")
}
test("creates runner with given arguments"){
val framework = new ScalaTestFramework
import framework.ScalaTestRunner
val loggers: Array[Logger] = Array(new TestLogger)
val runner = framework.testRunner(Thread.currentThread.getContextClassLoader, loggers).asInstanceOf[ScalaTestRunner]
assert(runner.testLoader == Thread.currentThread.getContextClassLoader)
assert(runner.loggers === loggers)
}
class TestLogger extends Logger{
def trace(t:Throwable){}
def error(msg:String){}
def warn(msg:String){}
def info(msg:String){}
def debug(msg:String){}
def ansiCodesSupported = false
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldBeExplicitlySpec.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.exceptions._
import org.scalatest.exceptions.TestFailedException
import org.scalactic.Explicitly
import org.scalactic.Equality
import Matchers._
class ShouldBeExplicitlySpec extends Spec with Explicitly {
implicit val e = new Equality[Int] {
def areEqual(a: Int, b: Any): Boolean = a != b
}
// Checking for beity with "be"
object `The be token` {
def `should do nothing when be` {
intercept[TestFailedException] { 1 should be (1) }
1 should be (1) (defaultEquality[Int])
1 should be (1) (decided by defaultEquality[Int])
(1 should be (1)) (defaultEquality[Int])
(1 should be (1)) (decided by defaultEquality[Int])
intercept[TestFailedException] { 1 shouldBe 1 }
(1 shouldBe 1) (defaultEquality[Int])
(1 shouldBe 1) (decided by defaultEquality[Int])
(1).shouldBe(1)(defaultEquality[Int])
(1).shouldBe(1)(decided by defaultEquality[Int])
}
def `should do nothing when not be and used with not` {
intercept[TestFailedException] { 1 should not { be (2) } }
intercept[TestFailedException] { 1 should not be (2) }
1 should not { be (2) } (defaultEquality[Int])
1 should not { be (2) } (decided by defaultEquality[Int])
(1 should not be (2)) (defaultEquality[Int])
(1 should not be (2)) (decided by defaultEquality[Int])
/*
intercept[TestFailedException] { 1 shouldNot { be (2) } }
intercept[TestFailedException] { 1 shouldNot be (2) }
1 shouldNot be (2) (defaultEquality[Int])
1 shouldNot be (2) (decided by defaultEquality[Int])
*/
}
def `should do nothing when be and used in a logical-and expression` {
intercept[TestFailedException] { 1 should (be (1) and be (2 - 1)) }
1 should (be (1) and be (2 - 1)) (decided by defaultEquality[Int])
1 should (be (1) (decided by defaultEquality[Int]) and be (2 - 1) (decided by defaultEquality[Int]))
}
def `should do nothing when be and used in multi-part logical expressions` {
// Just to make sure these work strung together
intercept[TestFailedException] { 1 should (be (1) and be (1) and be (1) and be (1)) }
intercept[TestFailedException] { 1 should (be (1) and be (1) or be (1) and be (1) or be (1)) }
intercept[TestFailedException] { 1 should (
be (1) and
be (1) or
be (1) and
be (1) or
be (1)
) }
1 should (be (1) and be (1) and be (1) and be (1)) (decided by defaultEquality[Int])
1 should (be (1) and be (1) or be (1) and be (1) or be (1)) (decided by defaultEquality[Int])
1 should (
be (1) and
be (1) or
be (1) and
be (1) or
be (1)
) (decided by defaultEquality[Int])
1 should (be (1) (decided by defaultEquality[Int]) and be (1) (decided by defaultEquality[Int]) and be (1) (decided by defaultEquality[Int]) and be (1) (decided by defaultEquality[Int]))
1 should (be (1) (decided by defaultEquality[Int]) and be (1) (decided by defaultEquality[Int]) or be (1) (decided by defaultEquality[Int]) and be (1) (decided by defaultEquality[Int]) or be (1) (decided by defaultEquality[Int]))
1 should (
be (1) (decided by defaultEquality[Int]) and
be (1) (decided by defaultEquality[Int]) or
be (1) (decided by defaultEquality[Int]) and
be (1) (decided by defaultEquality[Int]) or
be (1) (decided by defaultEquality[Int])
)
}
def `should do nothing when be and used in a logical-or expression` {
intercept[TestFailedException] { 1 should { be (1) or be (2 - 1) } }
1 should (be (1) or be (2 - 1)) (decided by defaultEquality[Int])
1 should { be (1) (decided by defaultEquality[Int]) or be (2 - 1) (decided by defaultEquality[Int]) }
}
def `should do nothing when not be and used in a logical-and expression with not` {
intercept[TestFailedException] { 1 should (not (be (2)) and not (be (3 - 1))) }
intercept[TestFailedException] { 1 should (not be (2) and (not be (3 - 1))) }
// Will back up on these MatcherGen1 and not ones, and do simpler MatcherGen1 and MatcherGen1 ones first
// intercept[TestFailedException] { 1 should (not be (2) and not be (3 - 1)) }
1 should (not (be (2)) and not (be (3 - 1))) (decided by defaultEquality[Int])
1 should (not be (2) and (not be (3 - 1))) (decided by defaultEquality[Int])
// 1 should (not be (2) and not be (3 - 1)) (decided by defaultEquality[Int])
1 should (not (be (2) (decided by defaultEquality[Int])) and not (be (3 - 1) (decided by defaultEquality[Int])))
1 should ((not be 2) (decided by defaultEquality[Int]) and (not be 3 - 1) (decided by defaultEquality[Int]))
}
/*
def `should do nothing when not be and used in a logical-or expression with not` {
1 should { not { be (2) } or not { be (3 - 1) }}
1 should { not be (2) or (not be (3 - 1)) }
1 should (not be (2) or not be (3 - 1))
}
def `should throw a TFE when not be` {
val caught1 = intercept[TestFailedException] {
1 should be (2)
}
assert(caught1.getMessage === "1 did not be 2")
val caught2 = intercept[TestFailedException] {
1 should not (not be (2))
}
assert(caught2.getMessage === "1 did not be 2")
val caught3 = intercept[TestFailedException] {
1 shouldBe 2
}
assert(caught3.getMessage === "1 did not be 2")
}
def `should throw a TFE when be but used with should not` {
val caught1 = intercept[TestFailedException] {
1 should not { be (1) }
}
assert(caught1.getMessage === "1 beed 1")
val caught2 = intercept[TestFailedException] {
1 should not be (1)
}
assert(caught2.getMessage === "1 beed 1")
val caught3 = intercept[TestFailedException] {
1 should not (not (not be (1)))
}
assert(caught3.getMessage === "1 beed 1")
}
def `should throw a TFE when not be and used in a logical-and expression` {
val caught = intercept[TestFailedException] {
1 should { be (5) and be (2 - 1) }
}
assert(caught.getMessage === "1 did not be 5")
}
def `should throw a TFE when not be and used in a logical-or expression` {
val caught = intercept[TestFailedException] {
1 should { be (5) or be (5 - 1) }
}
assert(caught.getMessage === "1 did not be 5, and 1 did not be 4")
}
def `should throw a TFE when be and used in a logical-and expression with not` {
val caught1 = intercept[TestFailedException] {
1 should { not { be (1) } and not { be (3 - 1) }}
}
assert(caught1.getMessage === "1 beed 1")
val caught2 = intercept[TestFailedException] {
1 should { not be (1) and (not be (3 - 1)) }
}
assert(caught2.getMessage === "1 beed 1")
val caught3 = intercept[TestFailedException] {
1 should (not be (1) and not be (3 - 1))
}
assert(caught3.getMessage === "1 beed 1")
val caught4 = intercept[TestFailedException] {
1 should { not { be (2) } and not { be (1) }}
}
assert(caught4.getMessage === "1 did not be 2, but 1 beed 1")
val caught5 = intercept[TestFailedException] {
1 should { not be (2) and (not be (1)) }
}
assert(caught5.getMessage === "1 did not be 2, but 1 beed 1")
val caught6 = intercept[TestFailedException] {
1 should (not be (2) and not be (1))
}
assert(caught6.getMessage === "1 did not be 2, but 1 beed 1")
}
def `should throw a TFE when be and used in a logical-or expression with not` {
val caught1 = intercept[TestFailedException] {
1 should { not { be (1) } or not { be (2 - 1) }}
}
assert(caught1.getMessage === "1 beed 1, and 1 beed 1")
val caught2 = intercept[TestFailedException] {
1 should { not be (1) or { not be (2 - 1) }}
}
assert(caught2.getMessage === "1 beed 1, and 1 beed 1")
val caught3 = intercept[TestFailedException] {
1 should (not be (1) or not be (2 - 1))
}
assert(caught3.getMessage === "1 beed 1, and 1 beed 1")
}
def `should put string differences in square bracket` {
val caught1 = intercept[TestFailedException] { "dummy" should be ("dunny") }
caught1.getMessage should be ("\"du[mm]y\" did not be \"du[nn]y\"")
val caught2 = intercept[TestFailedException] { "dummy" should be ("dunny") }
caught2.getMessage should be ("\"du[mm]y\" was not be to \"du[nn]y\"")
val caught3 = intercept[TestFailedException] { "hi there mom" should === ("high there mom") }
caught3.getMessage should === ("\"hi[] there mom\" was not be to \"hi[gh] there mom\"")
}
def `should not put string differences in square bracket` {
val caught1 = intercept[TestFailedException] { "dummy" should not be "dummy" }
caught1.getMessage should be ("\"dummy\" beed \"dummy\"")
val caught2 = intercept[TestFailedException] { "dummy" should not be "dummy" }
caught2.getMessage should be ("\"dummy\" was be to \"dummy\"")
}
def `should be usable when the left expression results in null` {
val npe = new NullPointerException
npe.getMessage should be (null)
}
def `should compare arrays structurally` {
val a1 = Array(1, 2, 3)
val a2 = Array(1, 2, 3)
val a3 = Array(4, 5, 6)
a1 should not be theSameInstanceAs (a2)
a1 should be (a2)
intercept[TestFailedException] {
a1 should be (a3)
}
}
def `should compare arrays deeply` {
val a1 = Array(1, Array("a", "b"), 3)
val a2 = Array(1, Array("a", "b"), 3)
val a3 = Array(1, Array("c", "d"), 3)
a1 should not be theSameInstanceAs (a2)
a1 should be (a2)
intercept[TestFailedException] {
a1 should be (a3)
}
}
def `should compare arrays containing nulls fine` {
val a1 = Array(1, Array("a", null), 3)
val a2 = Array(1, Array("a", null), 3)
val a3 = Array(1, Array("c", "d"), 3)
a1 should not be theSameInstanceAs (a2)
a1 should be (a2)
intercept[TestFailedException] {
a1 should be (a3)
}
intercept[TestFailedException] {
a3 should be (a1)
}
}
def `should compare nulls in a satisfying manner` {
val n1: String = null
val n2: String = null
n1 should be (n2)
intercept[TestFailedException] {
n1 should be ("hi")
}
intercept[TestFailedException] {
"hi" should be (n1)
}
val a1 = Array(1, 2, 3)
intercept[TestFailedException] {
n1 should be (a1)
}
intercept[TestFailedException] {
a1 should be (n1)
}
}
*/
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/Stopper.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
/**
* Trait whose instances can accept a stop request and indicate whether a stop has already been requested.
*
* <p>
* This is passed in
* to the <code>run</code> method of <a href="Suite.html"><code>Suite</code></a>, so that running suites of tests can be
* requested to stop early.
* </p>
*
* @author <NAME>
*/
trait Stopper {
/**
* Indicates whether a stop has been requested.
*
* <p>
* Call this method
* to determine whether a running test should stop. The <code>run</code> method of any <code>Suite</code>, or
* code invoked by <code>run</code>, should periodically check the
* stop requested function. If <code>true</code>,
* the <code>run</code> method should interrupt its work and simply return.
* </p>
*
* @return true if a stop has been requested
*/
def stopRequested: Boolean
/**
* Request that the current run stop.
*
* <p>
* Invoking this method is like pulling the stop-request chord in a streetcar. It requests a stop, but in no
* way forces a stop. The running suite of tests decides when and how (and if) to respond to a stop request.
* ScalaTest's style traits periodically check the <code>stopRequested</code> method of the passed <code>Stopper</code>,
* and if a stop has been requested, terminates gracefully.
* </p>
*/
def requestStop()
}
/**
* Companion object to Stopper that holds a factory method that produces a new <code>Stopper</code> whose
* <code>stopRequested</code> method returns false until after its <code>requestStop</code> has been
* invoked.
*/
object Stopper {
private class DefaultStopper extends Stopper {
@volatile private var stopWasRequested = false
def stopRequested: Boolean = stopWasRequested
def requestStop() {
stopWasRequested = true
}
}
/**
* Factory method that produces a new <code>Stopper</code> whose
* <code>stopRequested</code> method returns false until after its <code>requestStop</code> has been
* invoked.
*
* <p>
* The <code>Stopper</code> returned by this method can be safely used by multiple threads concurrently.
* </p>
*
* @return a new default stopper
*/
def default: Stopper = new DefaultStopper
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/ArrayWrapper.scala | <filename>scalactic/src/main/scala/org/scalactic/ArrayWrapper.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
/**
* This wrapper gives better toString (Array(x, x, x)) as compared to Scala default one (WrappedArray(x, x, x)).
*/
private[org] class ArrayWrapper[T](underlying: Array[T]) extends Traversable[T] {
def foreach[U](f: (T) => U) {
var index = 0
while (index < underlying.length) {
index += 1
f(underlying(index - 1))
}
}
// Need to prettify the array's toString, because by the time it gets to decorateToStringValue, the array
// has been wrapped in this Traversable and so it won't get prettified anymore by FailureMessages.decorateToStringValue.
override def toString: String = FailureMessages.decorateToStringValue(underlying)
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/tools/ProgressBarPanel.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.tools
import org.scalatest.Resources
import java.awt.BorderLayout
import java.awt.Dimension
import java.net.URL
import javax.swing.border.BevelBorder
import javax.swing.ImageIcon
import javax.swing.JLabel
import javax.swing.JPanel
/**
* A JPanel that shows the progress bar as tests are running, or a
* 'doing discovery' message with an animated icon if discovery is in
* process.
*/
private[scalatest] class ProgressBarPanel() extends JPanel {
private val progressBar = new ColorBar()
private val discoPanel = new JPanel
private val discoJLabel = new JLabel
private val discoImageURL: URL =
getClass.getClassLoader.getResource("images/inProgress.gif")
setLayout(new BorderLayout())
setBorder(new BevelBorder(BevelBorder.LOWERED))
add(progressBar, BorderLayout.CENTER)
discoJLabel.setIcon(new ImageIcon(discoImageURL))
discoPanel.add(discoJLabel)
//
// This prevents resizing of the panel when switching between
// the color bar and the discovery message panel.
//
setPreferredSize(
new Dimension(
getPreferredSize.getWidth.toInt,
discoPanel.getPreferredSize.getHeight.toInt + 4))
//
// Replaces progress bar with discovery message.
//
def discoveryStarting() {
remove(progressBar)
add(discoPanel, BorderLayout.WEST)
// change text after adding panel in order to get panel to show up
discoJLabel.setText("")
discoJLabel.setText(Resources.doingDiscovery)
}
private def showProgressBar() {
remove(discoPanel)
add(progressBar, BorderLayout.CENTER)
}
def runAborted() {
showProgressBar()
progressBar.setRed()
}
def discoveryCompleted() {
showProgressBar()
}
def runStarting(testCount: Int) {
progressBar.setMax(testCount)
progressBar.setValue(0)
progressBar.setGreen()
}
def setTestsRun(testsCompletedCount: Int) {
progressBar.setValue(testsCompletedCount)
}
def suiteAborted() {
progressBar.setRed()
}
def testFailed(testsCompletedCount: Int) {
progressBar.setRed()
setTestsRun(testsCompletedCount)
}
def reset() {
showProgressBar()
progressBar.setGray()
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/matchers/TypeMatcherHelper.scala | <filename>scalatest/src/main/scala/org/scalatest/matchers/TypeMatcherHelper.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.matchers
import org.scalatest.{UnquotedString, Suite, FailureMessages, Resources}
import org.scalactic.Prettifier
import org.scalatest.MatchersHelper._
import org.scalatest.words.{ResultOfAnTypeInvocation, ResultOfATypeInvocation}
/**
* <code>TypeMatcherHelper</code> is called by <code>TypeMatcherMacro</code> to support <code>a [Type]</code> and <code>an [Type]</code> syntax.
*/
object TypeMatcherHelper {
/**
* Create a type matcher for the given <code>ResultOfATypeInvocation</code>.
*
* @param aType an instance of <code>ResultOfATypeInvocation</code>
* @return a type <code>Matcher</code>
*/
def aTypeMatcher(aType: ResultOfATypeInvocation[_]): Matcher[Any] =
new Matcher[Any] {
def apply(left: Any): MatchResult = {
val clazz = aType.clazz
MatchResult(
clazz.isAssignableFrom(left.getClass),
Resources.rawWasNotAnInstanceOf,
Resources.rawWasAnInstanceOf,
Vector(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName)),
Vector(left, UnquotedString(clazz.getName))
)
}
override def toString: String = "be (" + Prettifier.default(aType) + ")"
}
/**
* Create a type matcher for the given <code>ResultOfAnTypeInvocation</code>.
*
* @param anType an instance of <code>ResultOfAnTypeInvocation</code>
* @return a type <code>Matcher</code>
*/
def anTypeMatcher(anType: ResultOfAnTypeInvocation[_]): Matcher[Any] =
new Matcher[Any] {
def apply(left: Any): MatchResult = {
val clazz = anType.clazz
MatchResult(
clazz.isAssignableFrom(left.getClass),
Resources.rawWasNotAnInstanceOf,
Resources.rawWasAnInstanceOf,
Vector(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName)),
Vector(left, UnquotedString(clazz.getName))
)
}
override def toString: String = "be (" + Prettifier.default(anType) + ")"
}
/**
* Create a negated type matcher for the given <code>ResultOfATypeInvocation</code>.
*
* @param aType an instance of <code>ResultOfATypeInvocation</code>
* @return a negated type <code>Matcher</code>
*/
def notATypeMatcher(aType: ResultOfATypeInvocation[_]): Matcher[Any] =
new Matcher[Any] {
def apply(left: Any): MatchResult = {
val clazz = aType.clazz
MatchResult(
!clazz.isAssignableFrom(left.getClass),
Resources.rawWasAnInstanceOf,
Resources.rawWasNotAnInstanceOf,
Vector(left, UnquotedString(clazz.getName)),
Vector(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName))
)
}
override def toString: String = "not be " + Prettifier.default(aType)
}
/**
* Create a negated type matcher for the given <code>ResultOfAnTypeInvocation</code>.
*
* @param anType an instance of <code>ResultOfAnTypeInvocation</code>
* @return a negated type <code>Matcher</code>
*/
def notAnTypeMatcher(anType: ResultOfAnTypeInvocation[_]): Matcher[Any] =
new Matcher[Any] {
def apply(left: Any): MatchResult = {
val clazz = anType.clazz
MatchResult(
!clazz.isAssignableFrom(left.getClass),
Resources.rawWasAnInstanceOf,
Resources.rawWasNotAnInstanceOf,
Vector(left, UnquotedString(clazz.getName)),
Vector(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName))
)
}
override def toString: String = "not be " + Prettifier.default(anType)
}
/**
* Check if the given <code>left</code> is an instance of the type as described in the given <code>ResultOfATypeInvocation</code>.
* A <code>TestFailedException</code> will be thrown if <code>left</code> is not an instance of the type given by <code>ResultOfATypeInvocation</code>.
*
* @param left the left-hand-side (LHS) to be checked for the type
* @param aType an instance of <code>ResultOfATypeInvocation</code>
*/
def checkAType(left: Any, aType: ResultOfATypeInvocation[_]) {
val clazz = aType.clazz
if (!clazz.isAssignableFrom(left.getClass)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, clazz.getName)
throw newTestFailedException(FailureMessages.wasNotAnInstanceOf(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName)))
}
}
/**
* Check if the given <code>left</code> is an instance of the type as described in the given <code>ResultOfAnTypeInvocation</code>.
* A <code>TestFailedException</code> will be thrown if <code>left</code> is not an instance of the type given by <code>ResultOfAnTypeInvocation</code>.
*
* @param left the left-hand-side (LHS) to be checked for the type
* @param anType an instance of <code>ResultOfAnTypeInvocation</code>
*/
def checkAnType(left: Any, anType: ResultOfAnTypeInvocation[_]) {
val clazz = anType.clazz
if (!clazz.isAssignableFrom(left.getClass)) {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(left, clazz.getName)
throw newTestFailedException(FailureMessages.wasNotAnInstanceOf(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName)))
}
}
/**
* Based on <code>shouldBeTrue</code> value, check if the given <code>left</code> is an instance of the type as described in the given <code>ResultOfATypeInvocation</code>.
* If <code>shouldBeTrue</code> is true, a <code>TestFailedException</code> will be thrown if <code>left</code> is not an instance of the type given by <code>ResultOfATypeInvocation</code>.
* If <code>shouldBeTrue</code> is false, a <code>TestFailedException</code> will be thrown if <code>left</code> is an instance of the type given by <code>ResultOfATypeInvocation</code>.
*
* @param left the left-hand-side (LHS) to be checked for the type
* @param aType an instance of <code>ResultOfATypeInvocation</code>
*/
def checkATypeShouldBeTrue(left: Any, aType: ResultOfATypeInvocation[_], shouldBeTrue: Boolean) {
val clazz = aType.clazz
if (clazz.isAssignableFrom(left.getClass) != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages.wasNotAnInstanceOf(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName))
else
FailureMessages.wasAnInstanceOf(left, UnquotedString(clazz.getName))
)
}
}
/**
* Based on <code>shouldBeTrue</code> value, check if the given <code>left</code> is an instance of the type as described in the given <code>ResultOfAnTypeInvocation</code>.
* If <code>shouldBeTrue</code> is true, a <code>TestFailedException</code> will be thrown if <code>left</code> is not an instance of the type given by <code>ResultOfAnTypeInvocation</code>.
* If <code>shouldBeTrue</code> is false, a <code>TestFailedException</code> will be thrown if <code>left</code> is an instance of the type given by <code>ResultOfAnTypeInvocation</code>.
*
* @param left the left-hand-side (LHS) to be checked for the type
* @param anType an instance of <code>ResultOfAnTypeInvocation</code>
*/
def checkAnTypeShouldBeTrue(left: Any, anType: ResultOfAnTypeInvocation[_], shouldBeTrue: Boolean) {
val clazz = anType.clazz
if (clazz.isAssignableFrom(left.getClass) != shouldBeTrue) {
throw newTestFailedException(
if (shouldBeTrue)
FailureMessages.wasNotAnInstanceOf(left, UnquotedString(clazz.getName), UnquotedString(left.getClass.getName))
else
FailureMessages.wasAnInstanceOf(left, UnquotedString(clazz.getName))
)
}
}
} |
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/FutureSugar.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.concurrent.Future
import scala.concurrent.ExecutionContext
/**
* 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 FutureSugar {
/**
* 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 Futureizer[T](theFuture: Future[T]) {
def validating(hd: T => Validation[ErrorMessage], tl: (T => Validation[ErrorMessage])*)(implicit executor: ExecutionContext): Future[T] = {
theFuture.flatMap { (o: T) =>
TrySugar.passOrFirstFail(o, hd :: tl.toList) match {
case Pass => theFuture
case Fail(errorMessage) => Future.failed(ValidationFailedException(errorMessage))
}
}
}
}
}
object FutureSugar extends FutureSugar
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/StatefulStatusSpec.scala | <filename>scalatest-test/src/test/scala/org/scalatest/StatefulStatusSpec.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
class StatefulStatusSpec extends fixture.Spec {
protected type FixtureParam = {
def setCompleted()
def isCompleted: Boolean
def succeeds(): Boolean
def setFailed()
def waitUntilCompleted()
def whenCompleted(f: Boolean => Unit)
}
override protected def withFixture(test: OneArgTest): Outcome = {
val status1 = new ScalaTestStatefulStatus
test(status1) match {
case Succeeded =>
val status2 = new StatefulStatus
test(status2)
case other => other
}
}
object `StatefulStatus ` {
def `should by default return false for isCompleted`(status: FixtureParam) {
import scala.language.reflectiveCalls
assert(!status.isCompleted)
}
def `should return true for isCompleted after completes() is called`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setCompleted()
assert(status.isCompleted)
}
def `should return true for succeeds() after completes() is called without fails()`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setCompleted()
assert(status.succeeds)
}
def `should return false for succeeds() after completes is called after fails()`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setFailed()
status.setCompleted()
assert(!status.succeeds)
}
def `waitUntilCompleted should not block after completes() is called`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setCompleted()
status.waitUntilCompleted()
}
def `should throw IllegalStateException when setFailed() is called after setCompleted() is set`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setCompleted()
intercept[IllegalStateException] {
status.setFailed()
}
}
def `should allow setCompleted() to be called multiple times`(status: FixtureParam) {
import scala.language.reflectiveCalls
status.setCompleted()
assert(status.isCompleted)
status.setCompleted()
assert(status.isCompleted)
status.setCompleted()
assert(status.isCompleted)
}
def `should invoke a function registered with whenCompleted, passing a succeeded value, after the status completes successfully`(status: FixtureParam) {
import scala.language.reflectiveCalls
@volatile var callbackInvoked = false
@volatile var succeeded = false
// register callback
status.whenCompleted { st =>
callbackInvoked = true
succeeded = st
}
// ensure it was not executed yet
assert(!callbackInvoked)
// complete the status
status.setCompleted()
// ensure it was executed
assert(callbackInvoked)
// ensure it passed the correct success value
assert(succeeded === true)
}
def `should invoke a function registered with whenCompleted, passing a failed value, after the status completes without success`(status: FixtureParam) {
import scala.language.reflectiveCalls
@volatile var callbackInvoked = false
@volatile var succeeded = true
// register callback
status.whenCompleted { st =>
callbackInvoked = true
succeeded = st
}
// ensure it was not executed yet
assert(!callbackInvoked)
// Fail it
status.setFailed()
// complete the status
status.setCompleted()
// ensure it was executed
assert(callbackInvoked)
// ensure it passed the correct success value
assert(succeeded === false)
}
def `should invoke multiple functions registered with whenCompleted, passing a succeeded value, after the status completes successfully`(status: FixtureParam) {
import scala.language.reflectiveCalls
// register two callbacks
// ensure neither was executed yet
// complete the status
// ensure both were executed
@volatile var firstCallbackInvoked = false
@volatile var secondCallbackInvoked = false
@volatile var firstSucceeded = false
@volatile var secondSucceeded = false
// register callback 1
status.whenCompleted { st =>
firstCallbackInvoked = true
firstSucceeded = st
}
// register callback 2
status.whenCompleted { st =>
secondCallbackInvoked = true
secondSucceeded = st
}
// ensure they were not executed yet
assert(!firstCallbackInvoked)
assert(!secondCallbackInvoked)
// complete the status
status.setCompleted()
// ensure they were executed
assert(firstCallbackInvoked)
assert(secondCallbackInvoked)
// ensure they were passed the correct success value
assert(firstSucceeded === true)
assert(secondSucceeded === true)
}
def `should invoke multiple functions registered with whenCompleted, passing a failed value, after the status completes without success`(status: FixtureParam) {
import scala.language.reflectiveCalls
// register two callbacks
// ensure neither was executed yet
// complete the status
// ensure both were executed
@volatile var firstCallbackInvoked = false
@volatile var secondCallbackInvoked = false
@volatile var firstSucceeded = true
@volatile var secondSucceeded = true
// register callback 1
status.whenCompleted { st =>
firstCallbackInvoked = true
firstSucceeded = st
}
// register callback 2
status.whenCompleted { st =>
secondCallbackInvoked = true
secondSucceeded = st
}
// ensure they were not executed yet
assert(!firstCallbackInvoked)
assert(!secondCallbackInvoked)
// Fail it
status.setFailed()
// complete the status
status.setCompleted()
// ensure they were executed
assert(firstCallbackInvoked)
assert(secondCallbackInvoked)
// ensure they were passed the correct success value
assert(firstSucceeded === false)
assert(secondSucceeded === false)
}
def `should be serializable`(status: FixtureParam) {
SharedHelpers.serializeRoundtrip(status)
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/MapShouldBeDefinedAtSpec.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 FailureMessages.decorateToStringValue
import Matchers._
import exceptions.TestFailedException
class MapShouldBeDefinedAtSpec extends Spec {
def wasDefinedAt(left: Any, right: Any): String =
decorateToStringValue(left) + " was defined at " + decorateToStringValue(right)
def wasNotDefinedAt(left: Any, right: Any): String =
decorateToStringValue(left) + " was not defined at " + decorateToStringValue(right)
def equaled(left: Any, right: Any): String =
decorateToStringValue(left) + " equaled " + decorateToStringValue(right)
def didNotEqual(left: Any, right: Any): String =
decorateToStringValue(left) + " did not equal " + decorateToStringValue(right)
object `PartialFunction ` {
val map = Map(6 -> "six", 8 -> "eight")
val map2 = Map(6 -> "enam", 8 -> "lapan")
object `should be definedAt` {
def `should do nothing when PartialFunction is defined at the specified value` {
map should be definedAt (6)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is not defined at the specified value` {
val caught = intercept[TestFailedException] {
map should be definedAt (0)
}
assert(caught.message === Some(wasNotDefinedAt(map, 0)))
assert(caught.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-and expression passed` {
map should (be definedAt (6) and be definedAt (8))
map should (be definedAt (6) and (be definedAt (8)))
map should (be (definedAt (6)) and be (definedAt (8)))
map should (equal (map) and be definedAt (8))
map should (equal (map) and (be definedAt (8)))
map should ((equal (map)) and be (definedAt (8)))
map should (be definedAt (6) and equal (map))
map should (be definedAt (6) and (equal (map)))
map should (be (definedAt (6)) and (equal (map)))
}
def `should throw TestFailedException with correct stack depth when first expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (be definedAt (0) and be definedAt (8))
}
assert(caught1.message === Some(wasNotDefinedAt(map, 0)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (be definedAt (0) and (be definedAt (8)))
}
assert(caught2.message === Some(wasNotDefinedAt(map, 0)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (be (definedAt (0)) and be (definedAt (8)))
}
assert(caught3.message === Some(wasNotDefinedAt(map, 0)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (equal (map2) and be definedAt (8))
}
assert(caught4.message === Some(didNotEqual(map, map2)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (equal (map2) and (be definedAt (8)))
}
assert(caught5.message === Some(didNotEqual(map, map2)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
map should ((equal (map2)) and be (definedAt (8)))
}
assert(caught6.message === Some(didNotEqual(map, map2)))
assert(caught6.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when second expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (be definedAt (8) and be definedAt (0))
}
assert(caught1.message === Some(wasDefinedAt(map, 8) + ", but " + wasNotDefinedAt(map, 0)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (be definedAt (8) and (be definedAt (0)))
}
assert(caught2.message === Some(wasDefinedAt(map, 8) + ", but " + wasNotDefinedAt(map, 0)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (be (definedAt (8)) and be (definedAt (0)))
}
assert(caught3.message === Some(wasDefinedAt(map, 8) + ", but " + wasNotDefinedAt(map, 0)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (be definedAt (8) and equal (map2))
}
assert(caught4.message === Some(wasDefinedAt(map, 8) + ", but " + didNotEqual(map, map2)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (be definedAt (8) and (equal (map2)))
}
assert(caught5.message === Some(wasDefinedAt(map, 8) + ", but " + didNotEqual(map, map2)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
map should (be (definedAt (8)) and (equal (map2)))
}
assert(caught6.message === Some(wasDefinedAt(map, 8) + ", but " + didNotEqual(map, map2)))
assert(caught6.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (be definedAt (0) and be definedAt (0))
}
assert(caught1.message === Some(wasNotDefinedAt(map, 0)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (be definedAt (0) and (be definedAt (0)))
}
assert(caught2.message === Some(wasNotDefinedAt(map, 0)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (be (definedAt (0)) and be (definedAt (0)))
}
assert(caught3.message === Some(wasNotDefinedAt(map, 0)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-or expression passed` {
map should (be definedAt (6) or be definedAt (8))
map should (be definedAt (6) or (be definedAt (8)))
map should (be (definedAt (6)) or be (definedAt (8)))
map should (equal (map) or be definedAt (8))
map should (equal (map) or (be definedAt (8)))
map should ((equal (map)) or be (definedAt (8)))
map should (be definedAt (6) or equal (map))
map should (be definedAt (6) or (equal (map)))
map should (be (definedAt (6)) or (equal (map)))
}
def `should do nothing when first expression in logical-or expression failed` {
map should (be definedAt (0) or be definedAt (8))
map should (be definedAt (0) or (be definedAt (8)))
map should (be (definedAt (0)) or be (definedAt (8)))
map should (equal (map2) or be definedAt (8))
map should (equal (map2) or (be definedAt (8)))
map should ((equal (map2)) or be (definedAt (8)))
map should (be definedAt (0) or equal (map))
map should (be definedAt (0) or (equal (map)))
map should (be (definedAt (0)) or (equal (map)))
}
def `should do nothing when second expressions in logical-or expression failed` {
map should (be definedAt (6) or be definedAt (0))
map should (be definedAt (6) or (be definedAt (0)))
map should (be (definedAt (6)) or be (definedAt (0)))
map should (equal (map) or be definedAt (0))
map should (equal (map) or (be definedAt (0)))
map should ((equal (map)) or be (definedAt (0)))
map should (be definedAt (6) or equal (map2))
map should (be definedAt (6) or (equal (map2)))
map should (be (definedAt (6)) or (equal (map2)))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-or expression failed` {
val caught1 = intercept[TestFailedException] {
map should (be definedAt (0) or be definedAt (0))
}
assert(caught1.message === Some(wasNotDefinedAt(map, 0) + ", and " + wasNotDefinedAt(map, 0)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (be definedAt (0) or (be definedAt (0)))
}
assert(caught2.message === Some(wasNotDefinedAt(map, 0) + ", and " + wasNotDefinedAt(map, 0)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (be (definedAt (0)) or be (definedAt (0)))
}
assert(caught3.message === Some(wasNotDefinedAt(map, 0) + ", and " + wasNotDefinedAt(map, 0)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (be definedAt (0) or equal (map2))
}
assert(caught4.message === Some(wasNotDefinedAt(map, 0) + ", and " + didNotEqual(map, map2)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (equal (map2) or (be definedAt (0)))
}
assert(caught5.message === Some(didNotEqual(map, map2) + ", and " + wasNotDefinedAt(map, 0)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `should not be definedAt` {
def `should do nothing when PartialFunction is not defined at the specified value` {
map should not be definedAt (0)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is defined at the specified value` {
val caught = intercept[TestFailedException] {
map should not be definedAt (8)
}
assert(caught.message === Some(wasDefinedAt(map, 8)))
assert(caught.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-and expression passed` {
map should (not be definedAt (0) and not be definedAt (0))
map should (not be definedAt (0) and (not be definedAt (0)))
map should (not be (definedAt (0)) and not be (definedAt (0)))
map should (not equal (map2) and not be definedAt (0))
map should (not equal (map2) and (not be definedAt (0)))
map should ((not equal (map2)) and not be (definedAt (0)))
map should (not be definedAt (0) and not equal (map2))
map should (not be definedAt (0) and (not equal (map2)))
map should (not be (definedAt (0)) and (not equal (map2)))
}
def `should throw TestFailedException with correct stack depth when first expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (not be definedAt (8) and not be definedAt (0))
}
assert(caught1.message === Some(wasDefinedAt(map, 8)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (not be definedAt (8) and (not be definedAt (0)))
}
assert(caught2.message === Some(wasDefinedAt(map, 8)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (not be (definedAt (8)) and not be (definedAt (0)))
}
assert(caught3.message === Some(wasDefinedAt(map, 8)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (not equal (map) and not be definedAt (0))
}
assert(caught4.message === Some(equaled(map, map)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (not equal (map) and (not be definedAt (8)))
}
assert(caught5.message === Some(equaled(map, map)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
map should ((not equal (map)) and not be (definedAt (8)))
}
assert(caught6.message === Some(equaled(map, map)))
assert(caught6.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when second expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (not be definedAt (0) and not be definedAt (8))
}
assert(caught1.message === Some(wasNotDefinedAt(map, 0) + ", but " + wasDefinedAt(map, 8)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (not be definedAt (0) and (not be definedAt (8)))
}
assert(caught2.message === Some(wasNotDefinedAt(map, 0) + ", but " + wasDefinedAt(map, 8)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (not be (definedAt (0)) and not be (definedAt (8)))
}
assert(caught3.message === Some(wasNotDefinedAt(map, 0) + ", but " + wasDefinedAt(map, 8)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (not be definedAt (0) and not equal (map))
}
assert(caught4.message === Some(wasNotDefinedAt(map, 0) + ", but " + equaled(map, map)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (not be definedAt (0) and (not equal (map)))
}
assert(caught5.message === Some(wasNotDefinedAt(map, 0) + ", but " + equaled(map, map)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
map should (not be (definedAt (0)) and (not equal (map)))
}
assert(caught6.message === Some(wasNotDefinedAt(map, 0) + ", but " + equaled(map, map)))
assert(caught6.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
map should (not be definedAt (8) and not be definedAt (8))
}
assert(caught1.message === Some(wasDefinedAt(map, 8)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (not be definedAt (8) and (not be definedAt (8)))
}
assert(caught2.message === Some(wasDefinedAt(map, 8)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (not be (definedAt (8)) and not be (definedAt (8)))
}
assert(caught3.message === Some(wasDefinedAt(map, 8)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-or expression passed` {
map should (not be definedAt (0) or not be definedAt (0))
map should (not be definedAt (0) or (not be definedAt (0)))
map should (not be (definedAt (0)) or not be (definedAt (0)))
map should (not equal (map2) or not be definedAt (0))
map should (not equal (map2) or (not be definedAt (0)))
map should ((not equal (map2)) or not be (definedAt (0)))
map should (not be definedAt (0) or not equal (map2))
map should (not be definedAt (0) or (not equal (map2)))
map should (not be (definedAt (0)) or (not equal (map2)))
}
def `should do nothing when first expression in logical-or expression failed` {
map should (not be definedAt (8) or not be definedAt (0))
map should (not be definedAt (8) or (not be definedAt (0)))
map should (not be (definedAt (8)) or not be (definedAt (0)))
map should (not equal (map) or not be definedAt (0))
map should (not equal (map) or (not be definedAt (0)))
map should ((not equal (map)) or not be (definedAt (0)))
map should (not be definedAt (8) or not equal (map2))
map should (not be definedAt (8) or (not equal (map2)))
map should (not be (definedAt (8)) or (not equal (map2)))
}
def `should do nothing when second expressions in logical-or expression failed` {
map should (not be definedAt (0) or not be definedAt (8))
map should (not be definedAt (0) or (not be definedAt (8)))
map should (not be (definedAt (0)) or not be (definedAt (8)))
map should (not equal (map2) or not be definedAt (8))
map should (not equal (map2) or (not be definedAt (8)))
map should ((not equal (map2)) or not be (definedAt (8)))
map should (not be definedAt (0) or not equal (map))
map should (not be definedAt (0) or (not equal (map)))
map should (not be (definedAt (0)) or (not equal (map)))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-or expression failed` {
val caught1 = intercept[TestFailedException] {
map should (not be definedAt (8) or not be definedAt (8))
}
assert(caught1.message === Some(wasDefinedAt(map, 8) + ", and " + wasDefinedAt(map, 8)))
assert(caught1.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
map should (not be definedAt (8) or (not be definedAt (8)))
}
assert(caught2.message === Some(wasDefinedAt(map, 8) + ", and " + wasDefinedAt(map, 8)))
assert(caught2.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
map should (not be (definedAt (8)) or not be (definedAt (8)))
}
assert(caught3.message === Some(wasDefinedAt(map, 8) + ", and " + wasDefinedAt(map, 8)))
assert(caught3.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
map should (not be definedAt (8) or not equal (map))
}
assert(caught4.message === Some(wasDefinedAt(map, 8) + ", and " + equaled(map, map)))
assert(caught4.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
map should (not equal (map) or (not be definedAt (8)))
}
assert(caught5.message === Some(equaled(map, map) + ", and " + wasDefinedAt(map, 8)))
assert(caught5.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `shouldNot be definedAt` {
def `should do nothing when PartialFunction is not defined at the specified value` {
map shouldNot be definedAt (0)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is defined at the specified value` {
val caught = intercept[TestFailedException] {
map shouldNot be definedAt (8)
}
assert(caught.message === Some(wasDefinedAt(map, 8)))
assert(caught.failedCodeFileName === Some("MapShouldBeDefinedAtSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldBeAnyTypeCheckSpec.scala | <filename>scalatest-test/src/test/scala/org/scalatest/ShouldBeAnyTypeCheckSpec.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.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 ShouldBeAnyTypeCheckSpec extends Spec with CheckedEquality {
object `the should be syntax should give a type error for suspicious types` {
object `for values` {
def `at the basic level` {
""""hi" should be ("hi")""" should compile
""""hi" shouldBe "hi"""" should compile
""""hi" should not be ("ho")""" should compile
""""hi" shouldNot be ("ho")""" should compile
"""1 should be ("hi")""" shouldNot typeCheck
"""1 shouldBe "hi"""" shouldNot typeCheck
"""1 should not be ("ho")""" shouldNot typeCheck
"""1 shouldNot be ("ho")""" shouldNot typeCheck
""""hi" should be (1)""" shouldNot typeCheck
""""hi" shouldBe 1""" shouldNot typeCheck
""""hi" should not be (1)""" shouldNot typeCheck
""""hi" shouldNot be (1)""" shouldNot typeCheck
}
def `when used solo in logical expressions` {
"1 should (be (1) and be (2 - 1))" should compile
"1 should (be (1) or be (2 - 1))" should compile
"1 should (not be (1) and be (2 - 1))" should compile
"1 should (not be (1) or be (2 - 1))" should compile
"1 should (be (1) and not be (2 - 1))" should compile
"1 should (be (1) or not be (2 - 1))" should compile
"1 should (not be (1) and not be (2 - 1))" should compile
"1 should (not be (1) or not be (2 - 1))" should compile
"""1 should (be (1) and be ("X"))""" shouldNot typeCheck
"""1 should (be (1) or be ("X"))""" shouldNot typeCheck
"""1 should (not be (1) and be ("X"))""" shouldNot typeCheck
"""1 should (not be (1) or be ("X"))""" shouldNot typeCheck
"""1 should (be (1) and not be ("X"))""" shouldNot typeCheck
"""1 should (be (1) or not be ("X"))""" shouldNot typeCheck
"""1 should (not be (1) and not be ("X"))""" shouldNot typeCheck
"""1 should (not be (1) or not be ("X"))""" shouldNot typeCheck
"""1 should (be ("X") and be (2 - 1))""" shouldNot typeCheck
"""1 should (be ("X") or be (2 - 1))""" shouldNot typeCheck
"""1 should (not be ("X") and be (2 - 1))""" shouldNot typeCheck
"""1 should (not be ("X") or be (2 - 1))""" shouldNot typeCheck
"""1 should (be ("X") and not be (2 - 1))""" shouldNot typeCheck
"""1 should (be ("X") or not be (2 - 1))""" shouldNot typeCheck
"""1 should (not be ("X") and not be (2 - 1))""" shouldNot typeCheck
"""1 should (not be ("X") or not be (2 - 1))""" shouldNot typeCheck
"""1 should (be ("X") and be ("Y"))""" shouldNot typeCheck
"""1 should (be ("X") or be ("Y"))""" shouldNot typeCheck
"""1 should (not be ("X") and be ("Y"))""" shouldNot typeCheck
"""1 should (not be ("X") or be ("Y"))""" shouldNot typeCheck
"""1 should (be ("X") and not be ("Y"))""" shouldNot typeCheck
"""1 should (be ("X") or not be ("Y"))""" shouldNot typeCheck
"""1 should (not be ("X") and not be ("Y"))""" shouldNot typeCheck
"""1 should (not be ("X") or not be ("Y"))""" shouldNot typeCheck
}
def `when used in larger logical expressions` {
"List(1) should (have length (1) and be (List(1, 2)))" should compile
"List(1) should (have length (1) or be (List(1, 2)))" should compile
"List(1) should (not have length (1) and be (List(1, 2)))" should compile
"List(1) should (not have length (1) or be (List(1, 2)))" should compile
"List(1) should (have length (1) and not be (List(1, 2)))" should compile
"List(1) should (have length (1) or not be (List(1, 2)))" should compile
"List(1) should (not have length (1) and not be (List(1, 2)))" should compile
"List(1) should (not have length (1) or not be (List(1, 2)))" should compile
"List(1) should (be (Vector(1)) and have length (1))" should compile
"List(1) should (be (Vector(1)) or have length (1))" should compile
"List(1) should (not be (Vector(1)) and have length (1))" should compile
"List(1) should (not be (Vector(1)) or have length (1))" should compile
"List(1) should (be (Vector(1)) and not have length (1))" should compile
"List(1) should (be (Vector(1)) or not have length (1))" should compile
"List(1) should (not be (Vector(1)) and not have length (1))" should compile
"List(1) should (not be (Vector(1)) or not have length (1))" should compile
"""List(1) should (have length (1) and be ("X"))""" shouldNot typeCheck
"""List(1) should (have length (1) or be ("X"))""" shouldNot typeCheck
"""List(1) should (not have length (1) and be ("X"))""" shouldNot typeCheck
"""List(1) should (not have length (1) or be ("X"))""" shouldNot typeCheck
"""List(1) should (have length (1) and not be ("X"))""" shouldNot typeCheck
"""List(1) should (have length (1) or not be ("X"))""" shouldNot typeCheck
"""List(1) should (not have length (1) and not be ("X"))""" shouldNot typeCheck
"""List(1) should (not have length (1) or not be ("X"))""" shouldNot typeCheck
"""List(1) should (be ("X") and have length (1))""" shouldNot typeCheck
"""List(1) should (be ("X") or have length (1))""" shouldNot typeCheck
"""List(1) should (not be ("X") and have length (1))""" shouldNot typeCheck
"""List(1) should (not be ("X") or have length (1))""" shouldNot typeCheck
"""List(1) should (be ("X") and not have length (1))""" shouldNot typeCheck
"""List(1) should (be ("X") or not have length (1))""" shouldNot typeCheck
"""List(1) should (not be ("X") and not have length (1))""" shouldNot typeCheck
"""List(1) should (not be ("X") or not have length (1))""" shouldNot typeCheck
}
def `when used in even larger multi-part logical expressions` {
"1 should (be (1) and be (1) and be (1) and be (1))" should compile
"1 should (be (1) and be (1) or be (1) and be (1) or be (1))" should compile
"""1 should (
be (1) and
be (1) or
be (1) and
be (1) or
be (1)
)""" should compile
"1 should (be (1) and be (1) and be >= (1) and be (1))" should compile
"1 should (be (1) and be (1) or be >= (1) and be (1) or be (1))" should compile
"""1 should (
be (1) and
be (1) or
be >= (1) and
be (1) or
be (1)
)""" should compile
"1 should (be (1) and be >= (1) and be (1) and be >= (1))" should compile
"1 should (be (1) and be >= (1) or be (1) and be >= (1) or be (1))" should compile
"""1 should (
be (1) and
be >= (1) or
be (1) and
be >= (1) or
be (1)
)""" should compile
"""1 should (be (1) and be ("hi") and be (1) and be (1))""" shouldNot typeCheck
"""1 should (be (1) and be (1) or be (1) and be ("hi") or be (1))""" shouldNot typeCheck
"""1 should (
be (1) and
be (1) or
be (1) and
be (1) or
be ("hi")
)""" shouldNot typeCheck
"""1 should (be ("hi") and be (1) and be >= (1) and be (1))""" shouldNot typeCheck
"""1 should (be (1) and be (1) or be >= (1) and be ("hi") or be (1))""" shouldNot typeCheck
"""1 should (
be (1) and
be ("hi") or
be >= (1) and
be (1) or
be (1)
)""" shouldNot typeCheck
"""1 should (be ("hi") and be >= (1) and be (new java.util.Date) and be >= (1))""" shouldNot typeCheck
"""1 should (be (1) and be >= (1) or be (1) and be >= (1) or be ("hi"))""" shouldNot typeCheck
"""1 should (
be (1) and
be >= (1) or
be (new java.util.Date) and
be >= (1) or
be (1)
)""" shouldNot typeCheck
}
def `when a wrongly typed explcit beity is provided` {
import org.scalactic.Explicitly._
import org.scalactic.StringNormalizations._
implicit val strEq = after being lowerCased
""""hi" should be ("Hi")""" should compile
""""hi" shouldNot be ("Hi") (decided by defaultEquality[String])""" should compile
""""hi" shouldNot be ("Hi") (defaultEquality[String])""" should compile
"""1 shouldNot be ("Hi") (defaultEquality[Int])""" shouldNot typeCheck
"""1 should be ("Hi") (defaultEquality[Int])""" shouldNot typeCheck
}
}
object `for collections` {
def `at the basic level` {
"""all (List("hi")) should be ("hi")""" should compile
"""all (List("hi")) shouldBe "hi"""" should compile
"""all (List("hi")) should not be ("ho")""" should compile
"""all (List("hi")) shouldNot be ("ho")""" should compile
"""all (List(1)) should be ("hi")""" shouldNot typeCheck
"""all (List(1)) shouldBe "hi"""" shouldNot typeCheck
"""all (List(1)) should not be ("ho")""" shouldNot typeCheck
"""all (List(1)) shouldNot be ("ho")""" shouldNot typeCheck
"""all (List("hi")) should be (1)""" shouldNot typeCheck
"""all (List("hi")) shouldBe 1""" shouldNot typeCheck
"""all (List("hi")) should not be (1)""" shouldNot typeCheck
"""all (List("hi")) shouldNot be (1)""" shouldNot typeCheck
}
def `when used solo in logical expressions` {
"all (List(1)) should (be (1) and be (2 - 1))" should compile
"all (List(1)) should (be (1) or be (2 - 1))" should compile
"all (List(1)) should (not be (1) and be (2 - 1))" should compile
"all (List(1)) should (not be (1) or be (2 - 1))" should compile
"all (List(1)) should (be (1) and not be (2 - 1))" should compile
"all (List(1)) should (be (1) or not be (2 - 1))" should compile
"all (List(1)) should (not be (1) and not be (2 - 1))" should compile
"all (List(1)) should (not be (1) or not be (2 - 1))" should compile
"""all (List(1)) should (be (1) and be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (be (1) or be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (not be (1) and be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (not be (1) or be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (be (1) and not be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (be (1) or not be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (not be (1) and not be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (not be (1) or not be ("X"))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") and be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") or be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") and be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") or be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") and not be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") or not be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") and not be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") or not be (2 - 1))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") and be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") or be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") and be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") or be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") and not be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (be ("X") or not be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") and not be ("Y"))""" shouldNot typeCheck
"""all (List(1)) should (not be ("X") or not be ("Y"))""" shouldNot typeCheck
}
def `when used in larger logical expressions` {
"all (List(List(1))) should (have length (1) and be (List(1, 2)))" should compile
"all (List(List(1)) )should (have length (1) or be (List(1, 2)))" should compile
"all (List(List(1))) should (not have length (1) and be (List(1, 2)))" should compile
"all (List(List(1))) should (not have length (1) or be (List(1, 2)))" should compile
"all (List(List(1))) should (have length (1) and not be (List(1, 2)))" should compile
"all (List(List(1))) should (have length (1) or not be (List(1, 2)))" should compile
"all (List(List(1))) should (not have length (1) and not be (List(1, 2)))" should compile
"all (List(List(1))) should (not have length (1) or not be (List(1, 2)))" should compile
"all (List(List(1))) should (be (Vector(1)) and have length (1))" should compile
"all (List(List(1))) should (be (Vector(1)) or have length (1))" should compile
"all (List(List(1))) should (not be (Vector(1)) and have length (1))" should compile
"all (List(List(1))) should (not be (Vector(1)) or have length (1))" should compile
"all (List(List(1))) should (be (Vector(1)) and not have length (1))" should compile
"all (List(List(1))) should (be (Vector(1)) or not have length (1))" should compile
"all (List(List(1))) should (not be (Vector(1)) and not have length (1))" should compile
"all (List(List(1))) should (not be (Vector(1)) or not have length (1))" should compile
"""all (List(List(1))) should (have length (1) and be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (have length (1) or be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (not have length (1) and be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (not have length (1) or be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (have length (1) and not be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (have length (1) or not be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (not have length (1) and not be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (not have length (1) or not be ("X"))""" shouldNot typeCheck
"""all (List(List(1))) should (be ("X") and have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (be ("X") or have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (not be ("X") and have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (not be ("X") or have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (be ("X") and not have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (be ("X") or not have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (not be ("X") and not have length (1))""" shouldNot typeCheck
"""all (List(List(1))) should (not be ("X") or not have length (1))""" shouldNot typeCheck
}
def `when used in even larger multi-part logical expressions` {
"1 should (be (1) and be (1) and be (1) and be (1))" should compile
"1 should (be (1) and be (1) or be (1) and be (1) or be (1))" should compile
"""1 should (
be (1) and
be (1) or
be (1) and
be (1) or
be (1)
)""" should compile
"all (List(1)) should (be (1) and be (1) and be >= (1) and be (1))" should compile
"all (List(1)) should (be (1) and be (1) or be >= (1) and be (1) or be (1))" should compile
"""all (List(1)) should (
be (1) and
be (1) or
be >= (1) and
be (1) or
be (1)
)""" should compile
"all (List(1)) should (be (1) and be >= (1) and be (1) and be >= (1))" should compile
"all (List(1)) should (be (1) and be >= (1) or be (1) and be >= (1) or be (1))" should compile
"""all (List(1)) should (
be (1) and
be >= (1) or
be (1) and
be >= (1) or
be (1)
)""" should compile
"""all (List(1)) should (be (1) and be ("hi") and be (1) and be (1))""" shouldNot typeCheck
"""all (List(1)) should (be (1) and be (1) or be (1) and be ("hi") or be (1))""" shouldNot typeCheck
"""all (List(1)) should (
be (1) and
be (1) or
be (1) and
be (1) or
be ("hi")
)""" shouldNot typeCheck
"""all (List(1)) should (be ("hi") and be (1) and be >= (1) and be (1))""" shouldNot typeCheck
"""all (List(1)) should (be (1) and be (1) or be >= (1) and be ("hi") or be (1))""" shouldNot typeCheck
"""all (List(1)) should (
be (1) and
be ("hi") or
be >= (1) and
be (1) or
be (1)
)""" shouldNot typeCheck
"""all (List(1)) should (be ("hi") and be >= (1) and be (new java.util.Date) and be >= (1))""" shouldNot typeCheck
"""all (List(1)) should (be (1) and be >= (1) or be (1) and be >= (1) or be ("hi"))""" shouldNot typeCheck
"""all (List(1)) should (
be (1) and
be >= (1) or
be (new java.util.Date) and
be >= (1) or
be (1)
)""" shouldNot typeCheck
}
}
}
}
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/Complex.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
case class Complex(real: Double, imaginary: Double)
object Complex {
import scala.language.implicitConversions
implicit def convertDouble(d: Double): Complex = Complex(d, 0.0)
implicit def convertInt(i: Int): Complex = Complex(i, 0.0)
implicit def convertDigitString(digits: DigitString): Complex = Complex(digits.toInt, 0.0)
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/OrderingEquality.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
/**
* A <code>HashingEquality[T]</code> that offers a <code>compare</code> method that indicates
* whether two objects of type <code>T</code> are greater than, less than, or equal to each other.
*
* <p>
* Instances of this trait must define a <em>total ordering</em> on objects of type <code>T</code> that
* is consistent with <code>areEqual</code> according to the following:
* </p>
*
* <ul>
* <li><em>consistency</em>: for any non-<code>null</code> values <code>x</code> and <code>y</code>, <code>(compare(a, b) == 0) == areEqual(x, y)</code> must return <code>true</code>.</li>
* <li><em>right-null</em>: For any non-<code>null</code> value <code>x</code>, <code>compare(x, null)</code> must throw <code>NullPointerException</code>.</li>
* <li><em>left-null</em>: For any non-<code>null</code> value <code>x</code>, <code>compare(null, x)</code> must throw <code>NullPointerException</code>.</li>
* <li><em>both-null</em>: <code>compare(null, null)</code> must throw <code>NullPointerException</code>.</li>
* </ul>
*/
trait OrderingEquality[A] extends HashingEquality[A] {
/**
* Returns an integer whose sign indicates how x compares to y.
*
* <p>
* The result sign has the following meaning:
* </p>
*
* <ul>
* <li>negative if x < y</li>
* <li>positive if x > y</li>
* <li>zero otherwise (if <code>areEqual(x, y)</code>)</li>
* </ul>
*
* <p>
* For more detail on the contract of this method, see the main documentation for this trait.
* </p>
*/
def compare(a: A, b: A): Int
// Actually the only way to do this is to make them implement areEqual in
// each case and ask them to do it right. Give them the template, but problem
// is that even optionOfA: Option[A] method is problematic. This means they
// need to implement compare and areEqual, and that's a pain. But otherwise
// I can't give them an OrdBox. Well I could make them write compareNotEqual.
// So compare always calls areEqual, which it can do, or areEquivalent, and if
// that's not the case, then it calls compareNotEqual, which actually does
// the deed. This way compare and areEqual will always be in sync. Or weirder still
// I could have one method that both areEqual and compare call? And you implement that?
// Something that takes an A and an Any, then pattern matches, and if it is ... but
// that was compare(a: A, b: Any), which caused me to run into trouble. Oh, yes, because
// if it is not an A, I can't give a value for comparing.
// Yes, need both areEqual and compare. Can't implement one in terms of
// the other because of the Any in areEqual, but you can't do a compare
// with an Any even if you wanted to, which you wouldn't. Could do something
// funky to try and reduce errors, like a optionOfA method that you implement
// areEqual in terms of, but that'll just slow down areEqual. I think it is better
// to just require users to implement both, and say they need to be consistent with
// each other, like equals and hashCode, or like Ordering's equiv and ==. That way
// people can implement each in the most efficient manner.
// Oh yes, the reason we need the Any is so we can provide an OrdBox that doesn't
// cast and hope what comes back is a ClassCastException.
// override def areEqual(a: A, b: Any): Boolean
/**
* Returns true if `a` <= `b` in the total order defined by this <code>OrderingEquality</code>.
*/
final def lteq(a: A, b: A): Boolean = compare(a, b) <= 0
/**
* Returns true if `a` >= `b` in the total order defined by this <code>OrderingEquality</code>.
*/
final def gteq(a: A, b: A): Boolean = compare(a, b) >= 0
/**
* Returns true if `a` < `b` in the total order defined by this <code>OrderingEquality</code>.
*/
final def lt(a: A, b: A): Boolean = compare(a, b) < 0
/**
* Returns true if `a` > `b` in the total order defined by this <code>OrderingEquality</code>.
*/
final def gt(a: A, b: A): Boolean = compare(a, b) > 0
/**
* Returns true if `a` == `b` in the total order defined by this <code>OrderingEquality</code>.
*/
// final def equiv(a: A, b: A): Boolean = compare(a, b) == 0 // Silly. Don't need this as it is redundant with areEquivalent.
/**
* Returns `a` if `a` >= `b`, otherwise `b`, according to the total order defined by this <code>OrderingEquality</code>.
*/
final def max(a: A, b: A): A = if (gteq(a, b)) a else b
/**
* Returns `a` if `a` <= `b`, otherwise `b`, according to the total order defined by this <code>OrderingEquality</code>.
*/
final def min(a: A, b: A): A = if (lteq(a, b)) a else b
}
object OrderingEquality {
implicit def defaultOrderingEqualityForString: OrderingEquality[String] =
new OrderingEquality[String] {
def compare(a: String, b: String): Int = a.compareTo(b)
def hashCodeFor(a: String): Int = a.hashCode
def areEqual(a: String, b: Any): Boolean =
b match {
case s: String => a == s
case _ => false
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/StringLoneElementSpec.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 SharedHelpers._
import FailureMessages.decorateToStringValue
import Matchers._
import LoneElement._
class StringLoneElementSpec extends Spec {
def didNotEqual(left: Any, right: Any): String =
decorateToStringValue(left) + " did not equal " + decorateToStringValue(right)
def wasNotEqualTo(left: Any, right: Any): String =
decorateToStringValue(left) + " was not equal to " + decorateToStringValue(right)
def notLoneElement(left: Any, size: Int): String =
"Expected " + decorateToStringValue(left) + " to contain exactly 1 element, but it has size " + size
object `The loneElement syntax` {
object `when used with List` {
def `should work with xs.loneElement and passed when should syntax is used and xs only contains one element and the one element passed the check` {
"9".loneElement should be ('9')
}
def `should work with xs.loneElement and passed when assert syntax is used and xs only contains one element and the one element passed the check` {
assert("9".loneElement == '9')
}
def `should throw TestFailedException with correct stack depth and message when should syntax is used and xs.loneElement contains one element but it failed the check` {
val e = intercept[exceptions.TestFailedException] {
"8".loneElement should be ('9')
}
e.failedCodeFileName should be (Some("StringLoneElementSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 3))
e.message should be (Some(wasNotEqualTo('8', '9')))
}
def `should throw TestFailedException with correct stack depth and message when assert syntax is used and xs.loneElement contains one element but it failed the check` {
val e = intercept[exceptions.TestFailedException] {
assert("8".loneElement == '9')
}
assert(e.failedCodeFileName === Some("StringLoneElementSpec.scala"))
assert(e.failedCodeLineNumber === Some(thisLineNumber - 3))
assert(e.message === Some(didNotEqual('8', '9')))
}
def `should throw TestFailedException with correct stack depth and message when should syntax is used and xs contains 0 element and xs.loneElement is called` {
val e = intercept[exceptions.TestFailedException] {
"".loneElement should be ('9')
}
e.failedCodeFileName should be (Some("StringLoneElementSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 3))
e.message should be (Some(notLoneElement("", 0)))
}
def `should throw TestFailedException with correct stack depth and message when assert syntax is used and xs contains 0 element and xs.loneElement is called` {
val e = intercept[exceptions.TestFailedException] {
assert("".loneElement == '9')
}
assert(e.failedCodeFileName == Some("StringLoneElementSpec.scala"))
assert(e.failedCodeLineNumber == Some(thisLineNumber - 3))
assert(e.message === Some(notLoneElement("", 0)))
}
def `should throw TestFailedException with correct stack depth and message when should syntax is used and xs contains > 1 elements and xs.loneElement is called` {
val e = intercept[exceptions.TestFailedException] {
"28".loneElement should be ('9')
}
e.failedCodeFileName should be (Some("StringLoneElementSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 3))
e.message should be (Some(notLoneElement("28", 2)))
}
def `should throw TestFailedException with correct stack depth and message when assert syntax is used and xs contains > 1 elements and xs.loneElement is called` {
val xs = List(10, 12)
val e = intercept[exceptions.TestFailedException] {
assert("28".loneElement == '9')
}
assert(e.failedCodeFileName === Some("StringLoneElementSpec.scala"))
assert(e.failedCodeLineNumber === Some(thisLineNumber - 3))
assert(e.message === Some(notLoneElement("28", 2)))
}
}
}
}
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/anyvals/PosZLongSpec.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.scalactic.Equality
import org.scalatest._
import org.scalatest.prop.NyayaGeneratorDrivenPropertyChecks._
import japgolly.nyaya.test.Gen
// SKIP-SCALATESTJS-START
import scala.collection.immutable.NumericRange
// SKIP-SCALATESTJS-END
import scala.collection.mutable.WrappedArray
import OptionValues._
import org.scalactic.StrictCheckedEquality
import scala.util.{Failure, Success, Try}
class PosZLongSpec extends FunSpec with Matchers with StrictCheckedEquality {
implicit val posZLongGen: Gen[PosZLong] =
for {i <- Gen.chooselong(1, Long.MaxValue)} yield PosZLong.from(i).get
implicit val intGen: Gen[Int] = Gen.int
implicit val longGen: Gen[Long] = Gen.long
implicit val shortGen: Gen[Short] = Gen.short
implicit val charGen: Gen[Char] = Gen.char
implicit val floatGen: Gen[Float] = Gen.float
implicit val doubleGen: Gen[Double] = Gen.double
implicit val byteGen: Gen[Byte] = Gen.byte
implicit def tryEquality[T]: Equality[Try[T]] = new Equality[Try[T]] {
override def areEqual(a: Try[T], b: Any): Boolean = a match {
case _: Success[_] => a == b
case Failure(ex) => b match {
case _: Success[_] => false
case Failure(otherEx) => ex.getClass == otherEx.getClass && ex.getMessage == otherEx.getMessage
case _ => false
}
}
}
describe("A PosZLong") {
describe("should offer a from factory method that") {
it("returns Some[PosZLong] if the passed Long is greater than or equal to 0") {
PosZLong.from(0L).value.value shouldBe 0L
PosZLong.from(50L).value.value shouldBe 50L
PosZLong.from(100L).value.value shouldBe 100L
}
it("returns None if the passed Long is NOT greater than or equal to 0") {
PosZLong.from(-1L) shouldBe None
PosZLong.from(-99L) shouldBe None
}
}
it("should have a pretty toString") {
PosZLong.from(42L).value.toString shouldBe "PosZLong(42)"
}
it("should return the same type from its unary_+ method") {
+PosZLong(3L) shouldEqual PosZLong(3L)
}
it("should be automatically widened to compatible AnyVal targets") {
"(PosZLong(3L): Int)" shouldNot typeCheck
(PosZLong(3L): Long) shouldEqual 3L
(PosZLong(3L): Float) shouldEqual 3.0F
(PosZLong(3L): Double) shouldEqual 3.0
"(PosZLong(3L): PosInt)" shouldNot typeCheck
"(PosZLong(3L): PosLong)" shouldNot typeCheck
"(PosZLong(3L): PosFloat)" shouldNot typeCheck
"(PosZLong(3L): PosDouble)" shouldNot typeCheck
"(PosZLong(3L): PosZInt)" shouldNot typeCheck
(PosZLong(3L): PosZLong) shouldEqual PosZLong(3L)
(PosZLong(3L): PosZFloat) shouldEqual PosZFloat(3.0F)
(PosZLong(3L): PosZDouble) shouldEqual PosZDouble(3.0)
}
describe("when a compatible AnyVal is passed to a + method invoked on it") {
it("should give the same AnyVal type back at compile time, and correct value at runtime") {
// When adding a "primitive"
val opInt = PosZLong(3L) + 3
opInt shouldEqual 6L
val opLong = PosZLong(3L) + 3L
opLong shouldEqual 6L
val opFloat = PosZLong(3L) + 3.0F
opFloat shouldEqual 6.0F
val opDouble = PosZLong(3L) + 3.0
opDouble shouldEqual 6.0
// When adding a Pos*
val opPosInt = PosZLong(3L) + PosInt(3)
opPosInt shouldEqual 6L
val opPosLong = PosZLong(3L) + PosLong(3L)
opPosLong shouldEqual 6L
val opPosFloat = PosZLong(3L) + PosFloat(3.0F)
opPosFloat shouldEqual 6.0F
val opPosDouble = PosZLong(3L) + PosDouble(3.0)
opPosDouble shouldEqual 6.0
// When adding a *PosZ
val opPosZ = PosZLong(3L) + PosZInt(3)
opPosZ shouldEqual 6L
val opPosZLong = PosZLong(3L) + PosZLong(3L)
opPosZLong shouldEqual 6L
val opPosZFloat = PosZLong(3L) + PosZFloat(3.0F)
opPosZFloat shouldEqual 6.0F
val opPosZDouble = PosZLong(3L) + PosZDouble(3.0)
opPosZDouble shouldEqual 6.0
}
}
describe("when created with apply method") {
it("should compile when 8 is passed in") {
"PosZLong(8)" should compile
PosZLong(8).value shouldEqual 8L
"PosZLong(8L)" should compile
PosZLong(8L).value shouldEqual 8L
}
it("should compile when 0 is passed in") {
"PosZLong(0)" should compile
PosZLong(0).value shouldEqual 0L
"PosZLong(0L)" should compile
PosZLong(0L).value shouldEqual 0L
}
it("should not compile when -8 is passed in") {
"PosZLong(-8)" shouldNot compile
"PosZLong(-8L)" shouldNot compile
}
it("should not compile when x is passed in") {
val a: Int = -8
"PosZLong(a)" shouldNot compile
val b: Long = -8L
"PosZLong(b)" shouldNot compile
}
}
describe("when specified as a plain-old Long") {
def takesPosZLong(pos: PosZLong): Long = pos.value
it("should compile when 8 is passed in") {
"takesPosZLong(8)" should compile
takesPosZLong(8) shouldEqual 8L
"takesPosZLong(8L)" should compile
takesPosZLong(8L) shouldEqual 8L
}
it("should compile when 0 is passed in") {
"takesPosZLong(0)" should compile
takesPosZLong(0) shouldEqual 0L
"takesPosZLong(0L)" should compile
takesPosZLong(0L) shouldEqual 0L
}
it("should not compile when -8 is passed in") {
"takesPosZLong(-8)" shouldNot compile
"takesPosZLong(-8L)" shouldNot compile
}
it("should not compile when x is passed in") {
val x: Int = -8
"takesPosZLong(x)" shouldNot compile
val b: Long = -8L
"takesPosZLong(b)" shouldNot compile
}
}
it("should offer a unary ~ method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
(~pzlong) shouldEqual (~(pzlong.toLong))
}
}
it("should offer a unary + method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
(+pzlong).toLong shouldEqual (+(pzlong.toLong))
}
}
it("should offer a unary - method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
(-pzlong) shouldEqual (-(pzlong.toLong))
}
}
it("should offer << methods that are consistent with Long") {
forAll { (pzlong: PosZLong, shift: Int) =>
pzlong << shift shouldEqual pzlong.toLong << shift
}
forAll { (pzlong: PosZLong, shift: Long) =>
pzlong << shift shouldEqual pzlong.toLong << shift
}
}
it("should offer >>> methods that are consistent with Long") {
forAll { (pzlong: PosZLong, shift: Int) =>
pzlong >>> shift shouldEqual pzlong.toLong >>> shift
}
forAll { (pzlong: PosZLong, shift: Long) =>
pzlong >>> shift shouldEqual pzlong.toLong >>> shift
}
}
it("should offer >> methods that are consistent with Long") {
forAll { (pzlong: PosZLong, shift: Int) =>
pzlong >> shift shouldEqual pzlong.toLong >> shift
}
forAll { (pzlong: PosZLong, shift: Long) =>
pzlong >> shift shouldEqual pzlong.toLong >> shift
}
}
it("should offer '<' comparison that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong < byte) shouldEqual (pzlong.toLong < byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong < short) shouldEqual (pzlong.toLong < short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong < char) shouldEqual (pzlong.toLong < char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong < int) shouldEqual (pzlong.toLong < int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong < long) shouldEqual (pzlong.toLong < long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong < float) shouldEqual (pzlong.toLong < float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong < double) shouldEqual (pzlong.toLong < double)
}
}
it("should offer '<=' comparison that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong <= byte) shouldEqual (pzlong.toLong <= byte)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong <= char) shouldEqual (pzlong.toLong <= char)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong <= short) shouldEqual (pzlong.toLong <= short)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong <= int) shouldEqual (pzlong.toLong <= int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong <= long) shouldEqual (pzlong.toLong <= long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong <= float) shouldEqual (pzlong.toLong <= float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong <= double) shouldEqual (pzlong.toLong <= double)
}
}
it("should offer '>' comparison that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong > byte) shouldEqual (pzlong.toLong > byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong > short) shouldEqual (pzlong.toLong > short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong > char) shouldEqual (pzlong.toLong > char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong > int) shouldEqual (pzlong.toLong > int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong > long) shouldEqual (pzlong.toLong > long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong > float) shouldEqual (pzlong.toLong > float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong > double) shouldEqual (pzlong.toLong > double)
}
}
it("should offer '>=' comparison that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong >= byte) shouldEqual (pzlong.toLong >= byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong >= short) shouldEqual (pzlong.toLong >= short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong >= char) shouldEqual (pzlong.toLong >= char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong >= int) shouldEqual (pzlong.toLong >= int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong >= long) shouldEqual (pzlong.toLong >= long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong >= float) shouldEqual (pzlong.toLong >= float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong >= double) shouldEqual (pzlong.toLong >= double)
}
}
it("should offer a '|' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong | byte) shouldEqual (pzlong.toLong | byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong | short) shouldEqual (pzlong.toLong | short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong | char) shouldEqual (pzlong.toLong | char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong | int) shouldEqual (pzlong.toLong | int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong | long) shouldEqual (pzlong.toLong | long)
}
}
it("should offer an '&' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong & byte) shouldEqual (pzlong.toLong & byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong & short) shouldEqual (pzlong.toLong & short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong & char) shouldEqual (pzlong.toLong & char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong & int) shouldEqual (pzlong.toLong & int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong & long) shouldEqual (pzlong.toLong & long)
}
}
it("should offer an '^' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong ^ byte) shouldEqual (pzlong.toLong ^ byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong ^ short) shouldEqual (pzlong.toLong ^ short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong ^ char) shouldEqual (pzlong.toLong ^ char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong ^ int) shouldEqual (pzlong.toLong ^ int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong ^ long) shouldEqual (pzlong.toLong ^ long)
}
}
it("should offer a '+' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong + byte) shouldEqual (pzlong.toLong + byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong + short) shouldEqual (pzlong.toLong + short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong + char) shouldEqual (pzlong.toLong + char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong + int) shouldEqual (pzlong.toLong + int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong + long) shouldEqual (pzlong.toLong + long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong + float) shouldEqual (pzlong.toLong + float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong + double) shouldEqual (pzlong.toLong + double)
}
}
it("should offer a '-' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong - byte) shouldEqual (pzlong.toLong - byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong - short) shouldEqual (pzlong.toLong - short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong - char) shouldEqual (pzlong.toLong - char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong - int) shouldEqual (pzlong.toLong - int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong - long) shouldEqual (pzlong.toLong - long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong - float) shouldEqual (pzlong.toLong - float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong - double) shouldEqual (pzlong.toLong - double)
}
}
it("should offer a '*' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
(pzlong * byte) shouldEqual (pzlong.toLong * byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
(pzlong * short) shouldEqual (pzlong.toLong * short)
}
forAll { (pzlong: PosZLong, char: Char) =>
(pzlong * char) shouldEqual (pzlong.toLong * char)
}
forAll { (pzlong: PosZLong, int: Int) =>
(pzlong * int) shouldEqual (pzlong.toLong * int)
}
forAll { (pzlong: PosZLong, long: Long) =>
(pzlong * long) shouldEqual (pzlong.toLong * long)
}
forAll { (pzlong: PosZLong, float: Float) =>
(pzlong * float) shouldEqual (pzlong.toLong * float)
}
forAll { (pzlong: PosZLong, double: Double) =>
(pzlong * double) shouldEqual (pzlong.toLong * double)
}
}
it("should offer a '/' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
Try(pzlong / byte) shouldEqual Try(pzlong.toLong / byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
Try(pzlong / short) shouldEqual Try(pzlong.toLong / short)
}
forAll { (pzlong: PosZLong, char: Char) =>
Try(pzlong / char) shouldEqual Try(pzlong.toLong / char)
}
forAll { (pzlong: PosZLong, int: Int) =>
Try(pzlong / int) shouldEqual Try(pzlong.toLong / int)
}
forAll { (pzlong: PosZLong, long: Long) =>
Try(pzlong / long) shouldEqual Try(pzlong.toLong / long)
}
forAll { (pzlong: PosZLong, float: Float) =>
Try(pzlong / float) shouldEqual Try(pzlong.toLong / float)
}
forAll { (pzlong: PosZLong, double: Double) =>
Try(pzlong / double) shouldEqual Try(pzlong.toLong / double)
}
}
it("should offer a '%' method that is consistent with Long") {
forAll { (pzlong: PosZLong, byte: Byte) =>
Try(pzlong % byte) shouldEqual Try(pzlong.toLong % byte)
}
forAll { (pzlong: PosZLong, short: Short) =>
Try(pzlong % short) shouldEqual Try(pzlong.toLong % short)
}
forAll { (pzlong: PosZLong, char: Char) =>
Try(pzlong % char) shouldEqual Try(pzlong.toLong % char)
}
forAll { (pzlong: PosZLong, int: Int) =>
Try(pzlong % int) shouldEqual Try(pzlong.toLong % int)
}
forAll { (pzlong: PosZLong, long: Long) =>
Try(pzlong % long) shouldEqual Try(pzlong.toLong % long)
}
forAll { (pzlong: PosZLong, float: Float) =>
Try(pzlong % float) shouldEqual Try(pzlong.toLong % float)
}
forAll { (pzlong: PosZLong, double: Double) =>
Try(pzlong % double) shouldEqual Try(pzlong.toLong % double)
}
}
it("should offer 'min' and 'max' methods that are consistent with Long") {
forAll { (pzlong1: PosZLong, pzlong2: PosZLong) =>
pzlong1.max(pzlong2).toLong shouldEqual pzlong1.toLong.max(pzlong2.toLong)
pzlong1.min(pzlong2).toLong shouldEqual pzlong1.toLong.min(pzlong2.toLong)
}
}
it("should offer a 'toBinaryString' method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
pzlong.toBinaryString shouldEqual pzlong.toLong.toBinaryString
}
}
it("should offer a 'toHexString' method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
pzlong.toHexString shouldEqual pzlong.toLong.toHexString
}
}
it("should offer a 'toOctalString' method that is consistent with Long") {
forAll { (pzlong: PosZLong) =>
pzlong.toOctalString shouldEqual pzlong.toLong.toOctalString
}
}
// SKIP-SCALATESTJS-START
it("should offer 'to' and 'until' method that is consistent with Long") {
def rangeEqual[T](a: NumericRange[T], b: NumericRange[T]): Boolean =
a.start == b.start && a.end == b.end && a.step == b.step
forAll { (pzlong: PosZLong, end: Long, step: Long) =>
rangeEqual(pzlong.until(end), pzlong.toLong.until(end)) shouldBe true
rangeEqual(pzlong.until(end, step), pzlong.toLong.until(end, step)) shouldBe true
rangeEqual(pzlong.to(end), pzlong.toLong.to(end)) shouldBe true
rangeEqual(pzlong.to(end, step), pzlong.toLong.to(end, step)) shouldBe true
}
}
// SKIP-SCALATESTJS-END
it("should offer widening methods for basic types that are consistent with Long") {
forAll { (pzlong: PosZLong) =>
def widen(value: Long): Long = value
widen(pzlong) shouldEqual widen(pzlong.toLong)
}
forAll { (pzlong: PosZLong) =>
def widen(value: Float): Float = value
widen(pzlong) shouldEqual widen(pzlong.toLong)
}
forAll { (pzlong: PosZLong) =>
def widen(value: Double): Double = value
widen(pzlong) shouldEqual widen(pzlong.toLong)
}
forAll { (pzlong: PosZLong) =>
def widen(value: PosZFloat): PosZFloat = value
widen(pzlong) shouldEqual widen(PosZFloat.from(pzlong.toLong).get)
}
forAll { (pzlong: PosZLong) =>
def widen(value: PosZDouble): PosZDouble = value
widen(pzlong) shouldEqual widen(PosZDouble.from(pzlong.toLong).get)
}
}
}
}
|
cquiroz/scalatest | project/GenInspectorsShorthands.scala | <reponame>cquiroz/scalatest<filename>project/GenInspectorsShorthands.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 scala.annotation.tailrec
trait GenInspectorsShorthandsBase {
import Generator._
import GenInspectors._
class DynamicErrorDetailTemplate(fileName: String, lineNumber: String, messageTemplate: Template, formatParams: String, useIndex: Boolean) extends Template {
override def toString =
"\" + new java.text.MessageFormat(\"at " + (if (useIndex) "index" else "key") + " {0}, " + messageTemplate + " (" + fileName + ":\" + " + lineNumber + " + \")\"" + ").format(" + formatParams + ") + \""
}
class DynamicFirstIndexErrorDetailTemplate(colType: String, errorFun: String, errorValue: String, fileName: String, lineNumber: String, messageTemplate: Template) extends
ErrorDetailTemplate("\" + getIndex(xs, " + errorFun + "(xs, " + errorValue + ")) + \"", fileName, lineNumber, messageTemplate)
class DynamicFirstElementTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
if (colType == "String")
"\" + decorateToStringValue(" + getErrorMessageValuesFunName(colType, errorFun) + "(xs, " + errorValue + ")) + \""
else
"\" + decorateToStringValue(" + errorFun + "(xs, " + errorValue + ")) + \""
}
class DynamicFirstArrayElementTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
"\" + decorateToStringValue(" + getErrorMessageValuesFunName(colType, errorFun) + "(xs, " + errorValue + ").deep) + \""
}
class DynamicFirstElementLengthTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
"\" + " + getErrorMessageValuesFunName(colType, errorFun) + "(xs, " + errorValue + ").length + \""
}
class DynamicFirstElementSizeTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
"\" + " + getErrorMessageValuesFunName(colType, errorFun) + "(xs, " + errorValue + ").size + \""
}
class DynamicFirstElementGetKeyTemplate(colType: String, colText: String, errorFun: String, errorValue: String, fileName: String, lineNumber: String, messageTemplate: Template) extends
ErrorDetailTemplate("\" + " + errorFun + "(xs, " + errorValue + ")." + (if (colText.contains("java")) "getKey" else "_1") + " + \"", fileName, lineNumber, messageTemplate) {
override val at: String = "key"
}
class DynamicNextIndexErrorDetailTemplate(errorValue: String, fileName: String, lineNumber: String, messageTemplate: Template, messageValuesFunName: String, useIndex: Boolean) extends
DynamicErrorDetailTemplate(fileName, lineNumber, messageTemplate, messageValuesFunName + "(itr, xs, " + errorValue + ")", useIndex)
class DynamicNextElementTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
if (colType == "String")
"\\\"\" + " + errorFun + "(itr, " + errorValue + ") + \"\\\""
else
"\" + " + errorFun + "(itr, " + errorValue + ") + \""
}
class DynamicNextArrayElementTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
"\" + " + errorFun + "[" + colType + "](itr, " + errorValue + ").deep + \""
}
class DynamicNextElementLengthTemplate(colType: String, errorFun: String, errorValue: String) extends Template {
override def toString =
"\" + " + errorFun + "[" + colType + "](itr, " + errorValue + ").length + \""
}
class InspectorShorthandsSucceedTemplate(name: String, condition: String, assertText: String) extends Template {
override def toString =
"def `" + name + " should succeed when " + condition + "` {\n" +
" " + assertText + "\n" +
"}\n"
}
class InspectorShorthandsForAllErrorTemplateWithCause(
colText: String, condition: String, assertText: String,
fileName: String, colType: String, errorFun: String,
errorValue: String, causeErrMsg: String, xsText: String,
useIndex: Boolean
) extends Template {
val causeErrorMessage = new SimpleMessageTemplate(causeErrMsg)
val errorMessage = new ForAllErrMsgTemplate("'all' inspection",
if (useIndex)
new DynamicFirstIndexErrorDetailTemplate(colType, getErrorMessageValuesFunName(colType, errorFun), errorValue, fileName, "assertLineNumber", causeErrorMessage)
else
new DynamicFirstElementGetKeyTemplate(colType, colText, errorFun, errorValue, fileName, "assertLineNumber", causeErrorMessage)
)
val testName = colText + " should throw TestFailedException with correct stack depth and message when " + condition
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkErrorAndCause(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ", \"" + causeErrorMessage + "\")\n" +
"}\n"
}
class ElementTemplate(count: Int) extends Template {
override def toString =
if (count == 0)
"no element"
else if (count == 1)
"1 element"
else
count + " elements"
}
def iteratorText(useIndex: Boolean, colText: String): String =
if (!useIndex && colText.contains("java")) "entrySet.iterator" else if (colText.contains("java")) "iterator" else "toIterator"
class InspectorShorthandsForAtLeastErrorTemplate(
colText: String, condition: String, assertText: String,
fileName: String, colType: String, errorFun: String, errorValue: String,
min: Int, totalCount: Int, passedCount: Int, detailErrorMessage: String,
xsText: String, useIndex: Boolean) extends Template {
val details = buildList(totalCount - passedCount, detailErrorMessage) map { errMsg => new DynamicNextIndexErrorDetailTemplate(errorValue, fileName, "assertLineNumber", new SimpleMessageTemplate(errMsg.toString), getErrorMessageValuesFunName(colType, errorFun), useIndex) }
val errorMessage = new ForAtLeastErrMsgTemplate("'atLeast(" + min + ")' inspection", (if (passedCount > 0) "only " else "") + new ElementTemplate(passedCount).toString, details)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class InspectorShorthandsForEveryErrorTemplate(
colText: String, condition: String, assertText: String,
fileName: String, colType: String, errorFun: String, errorValue: String,
totalCount: Int, passedCount: Int, detailErrorMessage: String,
xsText: String, useIndex: Boolean) extends Template {
val details = buildList(totalCount - passedCount, detailErrorMessage) map { errMsg => new DynamicNextIndexErrorDetailTemplate(errorValue, fileName, "assertLineNumber", new SimpleMessageTemplate(errMsg.toString), getErrorMessageValuesFunName(colType, errorFun), useIndex) }
val errorMessage = new ForEveryErrMsgTemplate("'every' inspection", details)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class InspectorShorthandsForExactlyErrorTemplate(
colText: String, condition: String, assertText: String,
fileName: String, colType: String, okFun: String, errorFun: String, errorValue: String,
count: Int, totalCount: Int, passedCount: Int, detailErrorMessage: String,
xsText: String, useIndex: Boolean) extends Template {
val details = buildList(totalCount - passedCount, detailErrorMessage) map { errMsg => new DynamicNextIndexErrorDetailTemplate(errorValue, fileName, "assertLineNumber", new SimpleMessageTemplate(errMsg.toString), getErrorMessageValuesFunName(colType, errorFun), useIndex) }
val errorMessage = new ForExactlyErrMsgTemplate("'exactly(" + count + ")' inspection", (if (passedCount > 0) "only " else "") + new ElementTemplate(passedCount).toString, okFun, errorFun, errorValue, colType, details)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class InspectorShorthandsForNoErrorTemplate(colText: String, condition: String, assertText: String,
fileName: String, colType: String, okFun: String, errorFun: String, errorValue: String,
xsText: String, useIndex: Boolean) extends Template {
val keyIndexFun =
if (useIndex)
"getIndex(xs, getFirst" + getErrorMessageValuesFunName(colType, okFun) + "(xs, " + errorValue + "))"
else
"getFirst" + getErrorMessageValuesFunName(colType, okFun) + "(xs, " + errorValue + ")." + (if (colText.contains("java")) "getKey" else "_1")
val errorMessage = new ForNoErrMsgTemplate("'no' inspection", "\" + " + keyIndexFun + " + \"", useIndex)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class InspectorShorthandsForBetweenErrorTemplate(colText: String, condition: String, assertText: String,
fileName: String, colType: String, okFun: String, errorFun: String, errorValue: String,
from: Int, upTo: Int, totalCount: Int, passedCount: Int, detailErrorMessage: String,
xsText: String, useIndex: Boolean) extends Template {
val details = buildList(totalCount - passedCount, detailErrorMessage) map { errMsg => new DynamicNextIndexErrorDetailTemplate(errorValue, fileName, "assertLineNumber", new SimpleMessageTemplate(errMsg.toString), getErrorMessageValuesFunName(colType, errorFun), useIndex) }
val errorMessage = new ForBetweenLessErrMsgTemplate("'between(" + from + ", " + upTo + ")' inspection", (if (passedCount > 0) "only " else "") + new ElementTemplate(passedCount).toString, okFun, errorFun, errorValue, colType, details)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class InspectorShorthandsForAtMostErrorTemplate(colText: String, condition: String, assertText: String,
fileName: String, colType: String, okFun: String, errorFun: String, errorValue: String,
max: Int, passedCount: Int, detailErrorMessage: String,
xsText: String, useIndex: Boolean) extends Template {
val errorMessage = new ForAtMostErrMsgTemplate("'atMost(" + max + ")' inspection", max, new ElementTemplate(passedCount).toString, okFun, errorFun, errorValue, colType)
override def toString =
"def `" + colText + " should throw TestFailedException with correct stack depth and message when " + condition + "` {\n" +
" val xs = " + colText + "\n" +
" val itr = xs." + iteratorText(useIndex, colText) + "\n" +
" val e = intercept[exceptions.TestFailedException] {\n" +
" " + assertText + "\n" +
" }\n" +
" val assertLineNumber = thisLineNumber - 2\n" +
" checkError(e, assertLineNumber, \"" + fileName + "\", " + splitMultilineErrorMessage(errorMessage.toString) + ")\n" +
"}\n"
}
class JavaColHelperMethodTemplate(methodName: String, javaColType: String) extends Template {
override def toString =
"def " + methodName + "[T](valueList: List[T]): " + javaColType + "[T] = {\n" +
" val col = new " + javaColType + "[T]()\n" +
" for (value <- valueList)\n" +
" col.add(value)\n" +
" col\n" +
"}\n"
}
class JavaColHelperMethodWithSizeTemplate(methodName: String, javaColType: String) extends Template {
override def toString =
"def " + methodName + "[T](valueList: List[T], size: Int): " + javaColType + "[T] = {\n" +
" val col = new " + javaColType + "[T](size)\n" +
" for (value <- valueList)\n" +
" col.add(value)\n" +
" col\n" +
"}\n"
}
class JavaMapHelperMethodTemplate(methodName: String, javaMapType: String) extends Template {
override def toString =
"def " + methodName + "[K, V](valueMap: Map[K, V]): " + javaMapType + "[K, V] = {\n" +
" val map = new " + javaMapType + "[K, V]()\n" +
" for ((key, value) <- valueMap)\n" +
" map.put(key, value)\n" +
" map\n" +
"}\n"
}
class TypeParameterlessJavaMapHelperMethodTemplate(methodName: String, javaMapType: String) extends Template {
override def toString =
"def " + methodName + "(valueMap: Map[String, String]): " + javaMapType + " = {\n" +
" val map = new " + javaMapType + "()\n" +
" for ((key, value) <- valueMap)\n" +
" map.put(key, value)\n" +
" map\n" +
"}\n"
}
class InspectorShorthandsHelpersTemplate extends Template {
override def toString =
"class EmptyBePropertyMatcher extends BePropertyMatcher[String] {\n" +
" def apply(left: String) = BePropertyMatchResult(left.isEmpty, \"empty\")\n" +
"}\n" +
"class StringLengthMatcher(expectedValue: Int) extends HavePropertyMatcher[String, Int] {\n" +
" def apply(value: String) = {\n" +
" new HavePropertyMatchResult(value.length == expectedValue, \"length\", expectedValue, value.length)\n" +
" }\n" +
"}\n" +
"val emptyMatcher = new EmptyBePropertyMatcher()\n" +
"def plength(expectedValue: Int) = new StringLengthMatcher(expectedValue)\n" +
"val theInstance = \"2\"\n" +
"def arrayToString(xs: GenTraversable[_]): String = FailureMessages.decorateToStringValue(xs)\n" +
"def checkErrorAndCause(e: exceptions.TestFailedException, assertLineNumber: Int, fileName: String, errorMessage: String, causeErrorMessage: String) {\n" +
" assert(e.failedCodeFileName == Some(fileName), e.failedCodeFileName + \" did not equal \" + Some(fileName))\n" +
" assert(e.failedCodeLineNumber == Some(assertLineNumber), e.failedCodeLineNumber + \" did not equal \" + Some(assertLineNumber))\n" +
" assert(e.message == Some(errorMessage), e.message + \" did not equal \" + Some(\nerrorMessage))\n" +
" e.getCause match {\n" +
" case tfe: exceptions.TestFailedException =>\n" +
" assert(tfe.failedCodeFileName == Some(fileName), tfe.failedCodeFileName + \" did not equal \" + Some(fileName))\n" +
" assert(tfe.failedCodeLineNumber == Some(assertLineNumber), tfe.failedCodeLineNumber + \" did not equal \" + Some(assertLineNumber))\n" +
" assert(tfe.message == Some(causeErrorMessage), tfe.message + \" did not equal \" + Some(causeErrorMessage))\n" +
" assert(tfe.getCause == null, tfe.getCause + \" was not null\")\n" +
" case other => fail(\"Expected cause to be TestFailedException, but got: \" + other)\n" +
" }\n" +
"}\n" +
"def checkError(e: exceptions.TestFailedException, assertLineNumber: Int, fileName: String, errorMessage: String) {\n" +
" assert(e.failedCodeFileName == Some(fileName), e.failedCodeFileName + \" did not equal \" + Some(fileName))\n" +
" assert(e.failedCodeLineNumber == Some(assertLineNumber), e.failedCodeLineNumber + \" did not equal \" + Some(assertLineNumber))\n" +
" assert(e.message == Some(errorMessage), e.message + \" did not equal \" + Some(\nerrorMessage))\n" +
"}\n" +
"def equal[T](left: T, right: T): Boolean = left == right\n" +
/*new SucceededIndexesHelperMethodTemplate +
new FailEarlySucceededIndexesHelperMethodTemplate +*/
new JavaColHelperMethodTemplate("javaArrayList", "java.util.ArrayList") +
new JavaColHelperMethodTemplate("javaHashSet", "java.util.HashSet") +
new JavaColHelperMethodTemplate("javaLinkedList", "java.util.LinkedList") +
new JavaColHelperMethodTemplate("javaStack", "java.util.Stack") +
new JavaColHelperMethodTemplate("javaTreeSet", "java.util.TreeSet") +
new JavaColHelperMethodTemplate("javaVector", "java.util.Vector") +
new JavaColHelperMethodWithSizeTemplate("javaArrayBlockingQueue", "java.util.concurrent.ArrayBlockingQueue") +
new JavaColHelperMethodTemplate("javaArrayDeque", "java.util.ArrayDeque") +
new JavaColHelperMethodTemplate("javaConcurrentLinkedQueue", "java.util.concurrent.ConcurrentLinkedQueue") +
new JavaColHelperMethodTemplate("javaConcurrentSkipListSet", "java.util.concurrent.ConcurrentSkipListSet") +
new JavaColHelperMethodTemplate("javaCopyOnWriteArrayList", "java.util.concurrent.CopyOnWriteArrayList") +
new JavaColHelperMethodTemplate("javaCopyOnWriteArraySet", "java.util.concurrent.CopyOnWriteArraySet") +
new JavaColHelperMethodTemplate("javaLinkedBlockingDeque", "java.util.concurrent.LinkedBlockingDeque") +
new JavaColHelperMethodTemplate("javaLinkedBlockingQueue", "java.util.concurrent.LinkedBlockingQueue") +
new JavaColHelperMethodTemplate("javaLinkedHashSet", "java.util.LinkedHashSet") +
new JavaColHelperMethodTemplate("javaPriorityBlockingQueue", "java.util.concurrent.PriorityBlockingQueue") +
new JavaColHelperMethodTemplate("javaPriorityQueue", "java.util.PriorityQueue") +
new JavaMapHelperMethodTemplate("javaHashMap", "java.util.HashMap") +
new JavaMapHelperMethodTemplate("javaTreeMap", "java.util.TreeMap") +
new JavaMapHelperMethodTemplate("javaHashtable", "java.util.Hashtable") +
new JavaMapHelperMethodTemplate("javaConcurrentHashMap", "java.util.concurrent.ConcurrentHashMap") +
new JavaMapHelperMethodTemplate("javaConcurrentSkipListMap", "java.util.concurrent.ConcurrentSkipListMap") +
new JavaMapHelperMethodTemplate("javaLinkedHashMap", "java.util.LinkedHashMap") +
new JavaMapHelperMethodTemplate("javaWeakHashMap", "java.util.WeakHashMap") +
new TypeParameterlessJavaMapHelperMethodTemplate("javaProperties", "java.util.Properties")
}
class EmptyTextMessageTemplate extends Template {
override def toString = "empty"
}
val empty = new EmptyTextMessageTemplate
// Helper methods
@tailrec
private def buildList[T](size: Int, element: T, list: List[T] = List.empty[T]): List[T] =
if (list.size < size) {
buildList(size, element, element :: list)
}
else
list
def splitMultilineErrorMessage(errorMessage: String) =
errorMessage.toString.split("\n").map("\"" + _).mkString("\n")
def genCol[T](colText: String, arrayXsText: String) =
List[(String, String)](
("Set(" + colText + ")", "xs"),
("List(" + colText + ")", "xs"),
("Seq(" + colText + ")", "xs"),
("Array(" + colText + ")", arrayXsText),
("IndexedSeq(" + colText + ")", "xs"),
("Vector(" + colText + ")", "xs"),
("Set(" + colText + ").par", "xs"),
("List(" + colText + ").par", "xs"),
("Seq(" + colText + ").par", "xs"),
("IndexedSeq(" + colText + ").par", "xs"),
("collection.mutable.Set(" + colText + ")", "xs"),
("new collection.mutable.ListBuffer() ++ List(" + colText + ")", "xs"),
("collection.mutable.Seq(" + colText + ")", "xs"),
("collection.mutable.IndexedSeq(" + colText + ")", "xs"),
("collection.mutable.Set(" + colText + ").par", "xs"),
("(new collection.mutable.ListBuffer() ++ List(" + colText + ")).par", "xs"),
("collection.mutable.Seq(" + colText + ").par", "xs"),
("collection.mutable.IndexedSeq(" + colText + ").par", "xs"),
("javaList(" + colText + ")", "xs"),
("javaSet(" + colText + ")", "xs"),
("Every(" + colText + ")", "xs")
)
def genNullableCol[T](colText: String, arrayXsText: String) =
List[(String, String)](
("Set(" + colText + ")", "xs"),
("List(" + colText + ")", "xs"),
("Seq(" + colText + ")", "xs"),
("Array(" + colText + ")", arrayXsText),
("IndexedSeq(" + colText + ")", "xs"),
("Vector(" + colText + ")", "xs"),
("Set(" + colText + ").par", "xs"),
("List(" + colText + ").par", "xs"),
("Seq(" + colText + ").par", "xs"),
("IndexedSeq(" + colText + ").par", "xs"),
("new collection.mutable.ListBuffer() ++ List(" + colText + ")", "xs"),
("collection.mutable.Seq(" + colText + ")", "xs"),
("collection.mutable.IndexedSeq(" + colText + ")", "xs"),
("(new collection.mutable.ListBuffer() ++ List(" + colText + ")).par", "xs"),
("collection.mutable.Seq(" + colText + ").par", "xs"),
("collection.mutable.IndexedSeq(" + colText + ").par", "xs"),
("javaList(" + colText + ")", "xs"),
("javaSet(" + colText + ")", "xs")
)
def genColCol[T](colType: String, colTexts: Array[String], arrayXsText: String) =
List[(String, String)](
("Set(" + colTexts.map("Set[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("List(" + colTexts.map("List[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("Seq(" + colTexts.map("Seq[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("Array[Array[" + colType + "]](" + colTexts.map("Array[" + colType + "](" + _ + ")").mkString(", ") + ")", "arrayToString(xs)"),
("IndexedSeq(" + colTexts.map("IndexedSeq[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("Vector(" + colTexts.map("Vector[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("Set(" + colTexts.map("Set[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("List(" + colTexts.map("List[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("Seq(" + colTexts.map("Seq[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("IndexedSeq(" + colTexts.map("IndexedSeq[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("collection.mutable.Set(" + colTexts.map("collection.mutable.Set[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("new collection.mutable.ListBuffer() ++ List(" + colTexts.map("new collection.mutable.ListBuffer[" + colType + "]() ++ List[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("collection.mutable.Seq(" + colTexts.map("collection.mutable.Seq[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("collection.mutable.IndexedSeq(" + colTexts.map("collection.mutable.IndexedSeq[" + colType + "](" + _ + ")").mkString(", ") + ")", "xs"),
("collection.mutable.Set(" + colTexts.map("collection.mutable.Set[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("(new collection.mutable.ListBuffer() ++ List(" + colTexts.map("(new collection.mutable.ListBuffer[" + colType + "]() ++ List[" + colType + "](" + _ + ")).par").mkString(", ") + ")).par", "xs"),
("collection.mutable.Seq(" + colTexts.map("collection.mutable.Seq[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs"),
("collection.mutable.IndexedSeq(" + colTexts.map("collection.mutable.IndexedSeq[" + colType + "](" + _ + ").par").mkString(", ") + ").par", "xs")
)
def genMap[T](colTexts: Array[String]) =
List[(String, String)](
(colTexts.map("Map(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("collection.mutable.Map(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.immutable.HashMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.mutable.HashMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.mutable.LinkedHashMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.immutable.ListMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.mutable.ListMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.mutable.OpenHashMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.immutable.SortedMap(" + _ + ")").mkString(", "), "xs"),
(colTexts.map("collection.immutable.TreeMap(" + _ + ")").mkString(", "), "xs")
)
def genColMap[T](mapText: String, arrayXsText: String) =
List[(String, String)](
("Set(" + mapText + ")", "xs"),
("List(" + mapText + ")", "xs"),
("Seq(" + mapText + ")", "xs"),
("Array(" + mapText + ")", "arrayToString(xs)"),
("IndexedSeq(" + mapText + ")", "xs"),
("Vector(" + mapText + ")", "xs"),
("Set(" + mapText + ").par", "xs"),
("List(" + mapText + ").par", "xs"),
("Seq(" + mapText + ").par", "xs"),
("IndexedSeq(" + mapText + ").par", "xs"),
("collection.mutable.Set(" + mapText + ")", "xs"),
("new collection.mutable.ListBuffer() ++ List(" + mapText + ")", "xs"),
("collection.mutable.Seq(" + mapText + ")", "xs"),
("collection.mutable.IndexedSeq(" + mapText + ")", "xs"),
("collection.mutable.Set(" + mapText + ").par", "xs"),
("(new collection.mutable.ListBuffer() ++ List(" + mapText + ")).par", "xs"),
("collection.mutable.Seq(" + mapText + ").par", "xs"),
("collection.mutable.IndexedSeq(" + mapText + ").par", "xs")
)
def genJavaCol[T](colTexts: Array[String]) =
List[(String, String)](
(colTexts.map("javaArrayList(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaHashSet(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaLinkedList(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaStack(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaTreeSet(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaVector(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaArrayBlockingQueue(" + _ + ", " + colTexts.length + ")").mkString(", ") , "xs"),
(colTexts.map("javaArrayDeque(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaConcurrentLinkedQueue(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaConcurrentSkipListSet(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaCopyOnWriteArrayList(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaCopyOnWriteArraySet(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaLinkedBlockingDeque(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaLinkedBlockingQueue(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaLinkedHashSet(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaPriorityBlockingQueue(" + _ + ")").mkString(", ") , "xs"),
(colTexts.map("javaPriorityQueue(" + _ + ")").mkString(", ") , "xs")
)
def genJavaColMap[T](mapText: String, arrayXsText: String) =
List[(String, String)](
("javaArrayList(List(" + mapText + "))", "xs"),
("javaHashSet(List(" + mapText + "))", "xs"),
("javaLinkedList(List(" + mapText + "))", "xs"),
("javaVector(List(" + mapText + "))", "xs"),
("javaArrayDeque(List(" + mapText + "))", "xs"),
("javaConcurrentLinkedQueue(List(" + mapText + "))", "xs"),
("javaCopyOnWriteArrayList(List(" + mapText + "))", "xs"),
("javaCopyOnWriteArraySet(List(" + mapText + "))", "xs"),
("javaLinkedBlockingDeque(List(" + mapText + "))", "xs"),
("javaLinkedBlockingQueue(List(" + mapText + "))", "xs"),
("javaLinkedHashSet(List(" + mapText + "))", "xs")
)
def genJavaMap[T](colTexts: Array[String], keyType: String, valueType: String) =
List[(String, String, String)](
(colTexts.map("javaHashMap(" + _ + ")").mkString(", ") , "xs", "java.util.HashMap[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaTreeMap(" + _ + ")").mkString(", ") , "xs", "java.util.TreeMap[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaHashtable(" + _ + ")").mkString(", ") , "xs", "java.util.Hashtable[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaConcurrentHashMap(" + _ + ")").mkString(", ") , "xs", "java.util.concurrent.ConcurrentHashMap[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaConcurrentSkipListMap(" + _ + ")").mkString(", ") , "xs", "java.util.concurrent.ConcurrentSkipListMap[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaLinkedHashMap(" + _ + ")").mkString(", ") , "xs", "java.util.LinkedHashMap[" + keyType + ", " + valueType + "]"),
(colTexts.map("javaWeakHashMap(" + _ + ")").mkString(", ") , "xs", "java.util.WeakHashMap[" + keyType + ", " + valueType + "]")/*,
(colTexts.map("javaProperties(" + _ + ")").mkString(", ") , "xs", "java.util.Properties")*/
)
def getFun(funString: String, right: Int): Int => Boolean = {
funString match {
case "indexElementNotEqual[Int]" => _ != right
case "indexElementEqual[Int]" => _ == right
case "indexElementNotEqual[String]" => _ != right
case "indexElementEqual[String]" => _ == right
case "indexElementNotEqual[(Int, Int)]" => _ != right
case "indexElementEqual[(Int, Int)]" => _ == right
case "indexElementNotEqual[Int, Int]" => _ != right
case "indexElementEqual[Int, Int]" => _ == right
case "indexElementNotEqual" => _ != right
case "indexElementEqual" => _ == right
case "indexElementLessThanEqual" => _ <= right
case "indexElementLessThan" => _ < right
case "indexElementMoreThanEqual" => _ >= right
case "indexElementMoreThan" => _ > right
}
}
def getSizeFun(funString: String, right: Int): String => Boolean = {
funString match {
case "indexElementSizeEqual[String]" => _.size == right
case "indexElementSizeNotEqual[String]" => _.size != right
case "indexElementSizeEqual[(Int, Int)]" => _.size == right
case "indexElementSizeNotEqual[(Int, Int)]" => _.size != right
case "indexElementSizeEqual[Int, Int]" => _.size == right
case "indexElementSizeNotEqual[Int, Int]" => _.size != right
case "indexElementSizeEqualGenTraversable[String]" => _.size == right
case "indexElementSizeNotEqualGenTraversable[String]" => _.size != right
}
}
def getFun(funString: String, right: String): String => Boolean = {
funString match {
case "indexElementNotEqual[String]" => _ != right
case "indexElementEqual[String]" => _ == right
case "indexElementNotEqual[(Int, Int)]" => _ != right
case "indexElementEqual[(Int, Int)]" => _ == right
case "indexElementNotEqual[Int, Int]" => _ != right
case "indexElementEqual[Int, Int]" => _ == right
case "indexElementNotRefEqual[String]" => _ != right
case "indexElementRefEqual[String]" => _ == right
case "indexElementIsEmpty" => _.isEmpty
case "indexElementIsNotEmpty" => !_.isEmpty
case "indexElementLengthEqual" => _.length == right.length
case "indexElementLengthNotEqual" => _.length != right.length
case "indexElementLengthNotEqualLength" => _.length != right.length
case "indexElementSizeEqual" => _.size == right.size
case "indexElementSizeNotEqual" => _.size != right.size
case "indexElementStartsWith" => _.startsWith(right)
case "indexElementNotStartsWith" => !_.startsWith(right)
case "indexElementEndsWith" => _.endsWith(right)
case "indexElementNotEndsWith" => !_.endsWith(right)
case "indexElementInclude" => _.indexOf(right) >= 0
case "indexElementNotInclude" => _.indexOf(right) < 0
case "indexElementMatches" => _.matches(right)
case "indexElementNotMatches" => !_.matches(right)
}
}
def getTraversableFun(funString: String, right: Any): List[String] => Boolean = {
funString match {
case "indexElementSizeEqualGenTraversable[String]" => _.size == right
case "indexElementSizeNotEqualGenTraversable[String]" => _.size != right
//case s: String if s.startsWith("_.exists") => _.exists(_ == right)
//case s: String if s.startsWith("!_.exists") => !_.exists(_ == right)
case "indexElementContainGenTraversable[String]" => _.contains(right)
case "indexElementNotContainGenTraversable[String]" => !_.contains(right)
}
}
def getMapFun(funString: String, right: Any): Map[String, String] => Boolean = {
funString match {
case "indexElementContainKey[String, String]" => _.exists(_._1 == right)
case "indexElementNotContainKey[String, String]" => !_.exists(_._1 == right)
case "indexElementContainValue[String, String]" => _.exists(_._2 == right)
case "indexElementNotContainValue[String, String]" => !_.exists(_._2 == right)
}
}
def getJavaColFun(funString: String, right: Any): List[String] => Boolean = {
funString match {
case "indexElementJavaColSizeEqual" => _.size == right
case "indexElementJavaColSizeNotEqual" => _.size != right
case "indexElementJavaColIsEmpty" => _.isEmpty
case "indexElementJavaColNotIsEmpty" => !_.isEmpty
case "indexElementJavaColContain" => _.contains(right)
case "indexElementJavaColNotContain" => !_.contains(right)
}
}
def getJavaMapFun(funString: String, right: Any): java.util.Map[String, String] => Boolean = {
funString match {
case "indexElementJavaMapIsEmpty" => _.isEmpty
case "indexElementJavaMapNotIsEmpty" => !_.isEmpty
case "indexElementJavaMapSizeEqual" => _.size == right
case "indexElementJavaMapSizeNotEqual" => _.size != right
case "indexElementJavaMapContainKey" => _.containsKey(right)
case "indexElementJavaMapNotContainKey" => !_.containsKey(right)
case "indexElementJavaMapContainValue" => _.containsValue(right)
case "indexElementJavaMapNotContainValue" => !_.containsValue(right)
}
}
def stdInt123Types(leftTemplateFun: (String, String) => Template, right: Int, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should equal' failed", " should equal (" + right + ")", "Equal[Int]", errorFunPrefix + "NotEqual[Int]", "" + right, (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not equal' failed", " should not equal " + right, "NotEqual[Int]", errorFunPrefix + "Equal[Int]", "" + right, (errorFun: String, errorValue: String) => new EqualedMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be' failed", " should be (" + right + ")", "Equal[Int]", errorFunPrefix + "NotEqual[Int]", "" + right, (errorFun: String, errorValue: String) => new WasNotEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be' failed", " should not be " + right, "NotEqual[Int]", errorFunPrefix + "Equal[Int]", "" + right, (errorFun: String, errorValue: String) => new WasEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be less than comparison' failed", " should be < " + right, "LessThan", errorFunPrefix + "MoreThanEqual", "" + right, (errorFun: String, errorValue: String) => new WasNotLessThanMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be less than comparison' failed", " should not be < (" + right + ")", "MoreThanEqual", errorFunPrefix + "LessThan", "" + right, (errorFun: String, errorValue: String) => new WasLessThanMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be less than or equal comparison' failed", " should be <= " + right, "LessThanEqual", errorFunPrefix + "MoreThan", "" + right, (errorFun: String, errorValue: String) => new WasNotLessThanOrEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be less than or equal comparison' failed", " should not be <= (" + right + ")", "MoreThan", errorFunPrefix + "LessThanEqual", "" + right, (errorFun: String, errorValue: String) => new WasLessThanOrEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be greater than comparison' failed", " should be > " + right, "MoreThan", errorFunPrefix + "LessThanEqual", "" + right, (errorFun: String, errorValue: String) => new WasNotGreaterThanMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be greater than comparison' failed", " should not be > (" + right + ")", "LessThanEqual", errorFunPrefix + "MoreThan", "" + right, (errorFun: String, errorValue: String) => new WasGreaterThanMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be greater than or equal comparison' failed", " should be >= " + right, "MoreThanEqual", errorFunPrefix + "LessThan", "" + right, (errorFun: String, errorValue: String) => new WasNotGreaterThanOrEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be greater than or equal comparison' failed", " should not be >= (" + right + ")", "LessThan", errorFunPrefix + "MoreThanEqual", "" + right, (errorFun: String, errorValue: String) => new WasGreaterThanOrEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString))
)
def stdNullStringTypes(leftTemplateFun: (String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should be null' failed", " should be (null)", "Equal[String]", errorFunPrefix + "NotEqual[String]", "null", (errorFun: String, errorValue: String) => new WasNotNullMessageTemplate(leftTemplateFun(errorFun, errorValue), autoQuoteString)),
("'should not be null' failed", " should not be null", "NotEqual[String]", errorFunPrefix + "Equal[String]", "null", (errorFun: String, errorValue: String) => new WasNullMessageTemplate)
)
def stdPropertyCheckTypes(expectedLengthSize:Int, leftTemplateFun: (String, String) => Template, targetTemplateFun: (String, String) => Template, leftLengthTemplateFun: (String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should be symbol' failed", " should be ('empty)", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be symbol' failed", " should not be 'empty", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should be property' failed", " should be (emptyMatcher)", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be property' failed", " should not be emptyMatcher", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should be a symbol' failed", " should be a 'empty", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotAMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be a symbol' failed", " should not be a ('empty)", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasAMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should be a property' failed", " should be a emptyMatcher", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotAMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be a property' failed", " should not be a (emptyMatcher)", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasAMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should be an symbol' failed", " should be an 'empty", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotAnMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be an symbol' failed", " should not be an ('empty)", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasAnMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should be an property' failed", " should be an emptyMatcher", "IsEmpty", errorFunPrefix + "IsNotEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasNotAnMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should not be an property' failed", " should not be an (emptyMatcher)", "IsNotEmpty", errorFunPrefix + "IsEmpty", "\"\"", (errorFun: String, errorValue: String) => new WasAnMessageTemplate(leftTemplateFun(errorFun, errorValue), empty, autoQuoteString)),
("'should have property' failed", " should have (plength(" + expectedLengthSize + "))", "LengthEqual", errorFunPrefix + "LengthNotEqualLength", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new PropertyHadUnexpectedValueMessageTemplate("length", 0, leftLengthTemplateFun(errorFun, errorValue), targetTemplateFun(errorFun, errorValue), autoQuoteString)),
("'should not have property' failed", " should not have plength(" + expectedLengthSize + ")", "LengthNotEqual", errorFunPrefix + "LengthEqual", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new PropertyHadExpectedValueMessageTemplate("length", 0, leftTemplateFun(errorFun, errorValue), autoQuoteString))
)
def stdLengthSizeCheckTypes(expectedLengthSize:Int, leftTemplateFun: (String, String) => Template, leftLengthTemplateFun: (String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should have length' failed", " should have length " + expectedLengthSize, "LengthEqual", errorFunPrefix + "LengthNotEqual", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new HadLengthInsteadOfExpectedLengthMessageTemplate(leftTemplateFun(errorFun, errorValue), leftLengthTemplateFun(errorFun, errorValue), 0, autoQuoteString)),
("'should not have length' failed", " should not have length (" + expectedLengthSize + ")", "LengthNotEqual", errorFunPrefix + "LengthEqual", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new HadLengthMessageTemplate(leftTemplateFun(errorFun, errorValue), 0, autoQuoteString)),
("'should have size' failed", " should have size " + expectedLengthSize, "SizeEqual", errorFunPrefix + "SizeNotEqual", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new HadSizeInsteadOfExpectedSizeMessageTemplate(leftTemplateFun(errorFun, errorValue), leftLengthTemplateFun(errorFun, errorValue), 0, autoQuoteString)),
("'should not have size' failed", " should not have size (" + expectedLengthSize + ")", "SizeNotEqual", errorFunPrefix + "SizeEqual", "" + expectedLengthSize, (errorFun: String, errorValue: String) => new HadSizeMessageTemplate(leftTemplateFun(errorFun, errorValue), 0, autoQuoteString))
)
def stdInstanceCheckTypes(leftTemplateFun: (String, String) => Template, right: Any, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should be theSameInstanceAs' failed", " should be theSameInstanceAs theInstance", "RefEqual[String]", errorFunPrefix + "NotRefEqual[String]", "theInstance", (errorFun: String, errorValue: String) => new WasNotTheSameInstanceAsMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be theSameInstanceAs' failed", " should not be theSameInstanceAs (theInstance)", "NotRefEqual[String]", errorFunPrefix + "RefEqual[String]", "theInstance", (errorFun: String, errorValue: String) => new WasTheSameInstanceAsMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString))
)
def stdStringCheckTypes(leftTemplateFun: (String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should startWith' failed", " should startWith (\"hello\")", "StartsWith", errorFunPrefix + "NotStartsWith", "hello", (errorFun: String, errorValue: String) => new DidNotStartWithSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "hello", autoQuoteString)),
("'should not startWith' failed", " should not startWith (\"hello\")", "NotStartsWith", errorFunPrefix + "StartsWith", "hello", (errorFun: String, errorValue: String) => new StartedWithSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "hello", autoQuoteString)),
("'should endWith' failed", " should endWith (\"!\")", "EndsWith", errorFunPrefix + "NotEndsWith", "!", (errorFun: String, errorValue: String) => new DidNotEndWithSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "!", autoQuoteString)),
("'should not endWith' failed", " should not endWith (\"!\")", "NotEndsWith", errorFunPrefix + "EndsWith", "!", (errorFun: String, errorValue: String) => new EndedWithSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "!", autoQuoteString)),
("'should include' failed", " should include (\"ell\")", "Include", errorFunPrefix + "NotInclude", "ell", (errorFun: String, errorValue: String) => new DidNotIncludeSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "ell", autoQuoteString)),
("'should not include' failed", " should not include \"ell\"", "NotInclude", errorFunPrefix + "Include", "ell", (errorFun: String, errorValue: String) => new IncludedSubstringMessageTemplate(leftTemplateFun(errorFun, errorValue), "ell", autoQuoteString)),
("'should startWith regex' failed", " should startWith regex \"hel*o\"", "StartsWith", errorFunPrefix + "NotStartsWith", "hello", (errorFun: String, errorValue: String) => new DidNotStartWithRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "hel*o".r, autoQuoteString)),
("'should not startWith regex' failed", " should not startWith regex (\"hel*o\")", "NotStartsWith", errorFunPrefix + "StartsWith", "hello", (errorFun: String, errorValue: String) => new StartedWithRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "hel*o".r, autoQuoteString)),
("'should endWith regex' failed", " should endWith regex \"!\"", "EndsWith", errorFunPrefix + "NotEndsWith", "!", (errorFun: String, errorValue: String) => new DidNotEndWithRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "!".r, autoQuoteString)),
("'should not endWith regex' failed", " should not endWith regex (\"!\")", "NotEndsWith", errorFunPrefix + "EndsWith", "!", (errorFun: String, errorValue: String) => new EndedWithRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "!".r, autoQuoteString)),
("'should include regex' failed", " should include regex \"ell\"", "Include", errorFunPrefix + "NotInclude", "ell", (errorFun: String, errorValue: String) => new DidNotIncludeRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "ell".r, autoQuoteString)),
("'should not include regex' failed", " should not include regex (\"ell\")", "NotInclude", errorFunPrefix + "Include", "ell", (errorFun: String, errorValue: String) => new IncludedRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "ell".r, autoQuoteString)),
("'should fullyMatch regex' failed", " should fullyMatch regex \"h.*!\"", "Matches", errorFunPrefix + "NotMatches", "h.*!", (errorFun: String, errorValue: String) => new DidNotFullyMatchRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "h.*!".r, autoQuoteString)),
("'should not fullyMatch regex' failed", " should not fullyMatch regex (\"h.*!\")", "NotMatches", errorFunPrefix + "Matches", "h.*!", (errorFun: String, errorValue: String) => new FullyMatchRegexMessageTemplate(leftTemplateFun(errorFun, errorValue), "h.*!".r, autoQuoteString))
)
def stdTraversablePropertyCheckTypes(leftTemplateFun: (String, String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'traversable should be symbol' failed", " should be ('empty)", "SizeEqualGenTraversable[String]", errorFunPrefix + "SizeNotEqualGenTraversable[String]", "0", (colType: String, errorFun: String, errorValue: String) => new WasNotMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString)),
("'traversable should not be symbol' failed", " should not be 'empty", "SizeNotEqualGenTraversable[String]", errorFunPrefix + "SizeEqualGenTraversable[String]", "0", (colType: String, errorFun: String, errorValue: String) => new WasMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString))
)
def stdTraversableCheckTypes(leftTemplateFun: (String, String, String) => Template, leftLengthTemplateFun: (String, String, String) => Template, size: Int, notSize: Int, containText: String, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'traversable should have size' failed", " should have size " + size, "SizeEqualGenTraversable[String]", errorFunPrefix + "SizeNotEqualGenTraversable[String]", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadSizeInsteadOfExpectedSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftLengthTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'traversable should not have size' failed", " should not have size (" + notSize +")", "SizeNotEqualGenTraversable[String]", errorFunPrefix + "SizeEqualGenTraversable[String]", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'traversable should have length' failed", " should have length " + size, "SizeEqualGenTraversable[String]", errorFunPrefix + "SizeNotEqualGenTraversable[String]", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadLengthInsteadOfExpectedLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftLengthTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'traversable should not have length' failed", " should not have length (" + notSize + ")", "SizeNotEqualGenTraversable[String]", errorFunPrefix + "SizeEqualGenTraversable[String]", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'traversable should contain' failed", " should contain (\"" + containText + "\")", "ContainGenTraversable[String]", errorFunPrefix + "NotContainGenTraversable[String]", "\"" + containText + "\"", containText, (colType: String, errorFun: String, errorValue: String) => new DidNotContainElementMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "hi", autoQuoteString)),
("'traversable should not contain' failed", " should not contain \"" + containText + "\"", "NotContainGenTraversable[String]", errorFunPrefix + "ContainGenTraversable[String]", "\"" + containText + "\"", containText, (colType: String, errorFun: String, errorValue: String) => new ContainedElementMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "hi", autoQuoteString))
)
def stdMapCheckTypes(leftTemplateFun: (String, String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'map should contain key' failed", " should contain key \"2\"", "ContainKey[String, String]", errorFunPrefix + "NotContainKey[String, String]", "\"2\"", "2", (colType: String, errorFun: String, errorValue: String) => new DidNotContainKeyMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "2", autoQuoteString)),
("'map should not contain key' failed", " should not contain key (\"2\")", "NotContainKey[String, String]", errorFunPrefix + "ContainKey[String, String]", "\"2\"", "2", (colType: String, errorFun: String, errorValue: String) => new ContainedKeyMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "2", autoQuoteString)),
("'map should contain value' failed", " should contain value \"two\"", "ContainValue[String, String]", errorFunPrefix + "NotContainValue[String, String]", "\"two\"", "two", (colType: String, errorFun: String, errorValue: String) => new DidNotContainValueMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "two", autoQuoteString)),
("'map should not contain value' failed", " should not contain value (\"two\")", "NotContainValue[String, String]", errorFunPrefix + "ContainValue[String, String]", "\"two\"", "two", (colType: String, errorFun: String, errorValue: String) => new ContainedValueMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "two", autoQuoteString))
)
def stdStringTypes(leftTemplateFun: (String, String) => Template, right: Char, errorFunPrefix: String, autoQuoteString: Boolean, useMessageFormat: Boolean) = {
val quote = if (useMessageFormat) "''" else "'"
List(
("'should equal' failed", " should equal ('" + right + "')", "Equal", errorFunPrefix + "NotEqual", "'" + right + "'", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(quote + right + quote), autoQuoteString)),
("'should not equal' failed", " should not equal '" + right + "'", "NotEqual", errorFunPrefix + "Equal", "'" + right + "'", (errorFun: String, errorValue: String) => new EqualedMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(quote + right + quote), autoQuoteString)),
("'should be' failed", " should be ('" + right + "')", "Equal", errorFunPrefix + "NotEqual", "'" + right + "'", (errorFun: String, errorValue: String) => new WasNotEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(quote + right + quote), autoQuoteString)),
("'should not be' failed", " should not be '" + right + "'", "NotEqual", errorFunPrefix + "Equal", "'" + right + "'", (errorFun: String, errorValue: String) => new WasEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(quote + right + quote), autoQuoteString))
)
}
def stdNumberMapTypes(leftTemplateFun: (String, String) => Template, right: Tuple2[_, _], errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should equal' failed", " should equal (" + right + ")", "Equal[(Int, Int)]", errorFunPrefix + "NotEqual[(Int, Int)]", "" + right, (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not equal' failed", " should not equal " + right, "NotEqual[(Int, Int)]", errorFunPrefix + "Equal[(Int, Int)]", "" + right, (errorFun: String, errorValue: String) => new EqualedMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should be' failed", " should be (" + right + ")", "Equal[(Int, Int)]", errorFunPrefix + "NotEqual[(Int, Int)]", "" + right, (errorFun: String, errorValue: String) => new WasNotEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString)),
("'should not be' failed", " should not be " + right, "NotEqual[(Int, Int)]", errorFunPrefix + "Equal[(Int, Int)]", "" + right, (errorFun: String, errorValue: String) => new WasEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), right, autoQuoteString))
)
def stdNumberJavaMapTypes(leftTemplateFun: (String, String) => Template, right: Tuple2[_, _], errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'should equal' failed", " should equal (org.scalatest.Entry(" + right._1 + ", " + right._2 + "))", "Equal[Int, Int]", errorFunPrefix + "NotEqual[Int, Int]", "org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(right._1 + "=" + right._2), autoQuoteString)),
("'should not equal' failed", " should not equal org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", "NotEqual[Int, Int]", errorFunPrefix + "Equal[Int, Int]", "org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", (errorFun: String, errorValue: String) => new EqualedMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(right._1 + "=" + right._2), autoQuoteString)),
("'should be' failed", " should be (org.scalatest.Entry(" + right._1 + ", " + right._2 + "))", "Equal[Int, Int]", errorFunPrefix + "NotEqual[Int, Int]", "org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", (errorFun: String, errorValue: String) => new WasNotEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(right._1 + "=" + right._2), autoQuoteString)),
("'should not be' failed", " should not be org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", "NotEqual[Int, Int]", errorFunPrefix + "Equal[Int, Int]", "org.scalatest.Entry(" + right._1 + ", " + right._2 + ")", (errorFun: String, errorValue: String) => new WasEqualToMessageTemplate(leftTemplateFun(errorFun, errorValue), UnquotedString(right._1 + "=" + right._2), autoQuoteString))
)
def stdJavaColCheckTypes(size: Int, notSize: Int, leftTemplateFun: (String, String, String) => Template, leftSizeTemplateFun: (String, String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'java collection should be symbol' failed", " should be ('empty)", "JavaColIsEmpty", errorFunPrefix + "JavaColNotIsEmpty", "0", None, (colType: String, errorFun: String, errorValue: String) => new WasNotMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString)),
("'java collection should not be symbol' failed", " should not be 'empty", "JavaColNotIsEmpty", errorFunPrefix + "JavaColIsEmpty", "0", None, (colType: String, errorFun: String, errorValue: String) => new WasMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString)),
("'java collection should have size' failed", " should have size " + size, "JavaColSizeEqual", errorFunPrefix + "JavaColSizeNotEqual", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadSizeInsteadOfExpectedSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftSizeTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'java collection should not have size' failed", " should not have size (" + notSize + ")", "JavaColSizeNotEqual", errorFunPrefix + "JavaColSizeEqual", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'java collection should have length' failed", " should have length " + size, "JavaColSizeEqual", errorFunPrefix + "JavaColSizeNotEqual", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadLengthInsteadOfExpectedLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftSizeTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'java collection should not have length' failed", " should not have length (" + notSize + ")", "JavaColSizeNotEqual", errorFunPrefix + "JavaColSizeEqual", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'java collection should contain' failed", " should contain (\"hi\")", "JavaColContain", errorFunPrefix + "JavaColNotContain", "\"hi\"", "hi", (colType: String, errorFun: String, errorValue: String) => new DidNotContainElementMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "hi", autoQuoteString)),
("'java collection should not contain' failed", " should not contain \"hi\"", "JavaColNotContain", errorFunPrefix + "JavaColContain", "\"hi\"", "hi", (colType: String, errorFun: String, errorValue: String) => new ContainedElementMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "hi", autoQuoteString))
)
def stdJavaMapCheckTypes(size: Int, notSize: Int, leftTemplateFun: (String, String, String) => Template, leftSizeTemplateFun: (String, String, String) => Template, errorFunPrefix: String, autoQuoteString: Boolean = true) =
List(
("'java map should be symbol' failed", " should be ('empty)", "JavaMapIsEmpty", errorFunPrefix + "JavaMapNotIsEmpty", "0", None, (colType: String, errorFun: String, errorValue: String) => new WasNotMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString)),
("'java map should not be symbol' failed", " should not be 'empty", "JavaMapNotIsEmpty", errorFunPrefix + "JavaMapIsEmpty", "0", None, (colType: String, errorFun: String, errorValue: String) => new WasMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), empty, autoQuoteString)),
("'java map should have size' failed", " should have size " + size, "JavaMapSizeEqual", errorFunPrefix + "JavaMapSizeNotEqual", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadSizeInsteadOfExpectedSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftSizeTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'java map should not have size' failed", " should not have size (" + notSize + ")", "JavaMapSizeNotEqual", errorFunPrefix + "JavaMapSizeEqual", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadSizeMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'java map should have length' failed", " should have length " + size, "JavaMapSizeEqual", errorFunPrefix + "JavaMapSizeNotEqual", "" + size, size, (colType: String, errorFun: String, errorValue: String) => new HadLengthInsteadOfExpectedLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), leftSizeTemplateFun(colType, errorFun, errorValue), 0, autoQuoteString)),
("'java map should not have length' failed", " should not have length (" + notSize + ")", "JavaMapSizeNotEqual", errorFunPrefix + "JavaMapSizeEqual", "" + notSize, notSize, (colType: String, errorFun: String, errorValue: String) => new HadLengthMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), 1, autoQuoteString)),
("'java map should contain key' failed", " should contain key \"b\"", "JavaMapContainKey", errorFunPrefix + "JavaMapNotContainKey", "\"b\"", "b", (colType: String, errorFun: String, errorValue: String) => new DidNotContainKeyMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "b", autoQuoteString)),
("'java map should not contain key' failed", " should not contain key (\"b\")", "JavaMapNotContainKey", errorFunPrefix + "JavaMapContainKey", "\"b\"", "b", (colType: String, errorFun: String, errorValue: String) => new ContainedKeyMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "b", autoQuoteString)),
("'java map should contain value' failed", " should contain value \"boom!\"", "JavaMapContainValue", errorFunPrefix + "JavaMapNotContainValue", "\"boom!\"", "boom!", (colType: String, errorFun: String, errorValue: String) => new DidNotContainValueMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "boom!", autoQuoteString)),
("'java map should not contain value' failed", " should not contain value (\"boom!\")", "JavaMapNotContainValue", errorFunPrefix + "JavaMapContainValue", "\"boom!\"", "boom!", (colType: String, errorFun: String, errorValue: String) => new ContainedValueMessageTemplate(leftTemplateFun(colType, errorFun, errorValue), "boom!", autoQuoteString))
)
def simpleMessageFun(errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{1}")
def lengthSimpleMessageFun(errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{2}")
def trvSimpleMessageFun(colType: String, errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{1}")
def trvLengthSimpleMessageFun(colType: String, errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{2}")
def trvSizeSimpleMessageFun(colType: String, errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{2}")
def quotedSimpleMessageFun(errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("{1}")
def quotedSimpleMessageFun2(errorFun: String, errorValue: String): Template = new SimpleMessageTemplate("\\\"{2}\\\"")
def filterSetLength(colText: String, condition: String): Boolean =
!(colText.startsWith("Set(") && condition == "'should have length' failed") &&
!(colText.startsWith("Set(") && condition == "'should not have length' failed") &&
!(colText.startsWith("collection.mutable.Set") && condition == "'should have length' failed") &&
!(colText.startsWith("collection.mutable.Set") && condition == "'should not have length' failed") &&
!(colText.startsWith("Set(") && condition == "'traversable should have length' failed") &&
!(colText.startsWith("Set(") && condition == "'traversable should not have length' failed") &&
!(colText.startsWith("collection.mutable.Set") && condition == "'traversable should have length' failed") &&
!(colText.startsWith("collection.mutable.Set") && condition == "'traversable should not have length' failed")
def filterJavaColLength(colText: String, condition: String): Boolean =
!(colText.contains("javaHashSet") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaHashSet") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaTreeSet") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaTreeSet") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaLinkedHashSet") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaLinkedHashSet") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaArrayBlockingQueue") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaArrayBlockingQueue") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaArrayDeque") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaArrayDeque") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaConcurrentSkipListSet") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaConcurrentSkipListSet") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaCopyOnWriteArraySet") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaCopyOnWriteArraySet") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaLinkedBlockingDeque") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaLinkedBlockingDeque") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaLinkedBlockingQueue") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaLinkedBlockingQueue") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaPriorityBlockingQueue") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaPriorityBlockingQueue") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaPriorityQueue") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaPriorityQueue") && condition == "'java collection should not have length' failed") &&
!(colText.contains("javaConcurrentLinkedQueue") && condition == "'java collection should have length' failed") &&
!(colText.contains("javaConcurrentLinkedQueue") && condition == "'java collection should not have length' failed")
def filterJavaMapLength(colText: String, condition: String): Boolean =
!(colText.contains("javaHashMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaHashMap") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaTreeMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaTreeMap") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaHashtable") && condition == "'java map should have length' failed") &&
!(colText.contains("javaHashtable") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaConcurrentHashMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaConcurrentHashMap") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaConcurrentSkipListMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaConcurrentSkipListMap") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaLinkedHashMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaLinkedHashMap") && condition == "'java map should not have length' failed") &&
!(colText.contains("javaWeakHashMap") && condition == "'java map should have length' failed") &&
!(colText.contains("javaWeakHashMap") && condition == "'java map should not have length' failed")
def filterArraySymbol(colText: String, condition: String): Boolean =
!(colText.startsWith("Array") && condition == "'traversable should not be symbol' failed")
def genInspectorShorthandsForAllSpecFile(targetDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("all(" + colText + ")", "all elements succeeded", "all(" + colText + ") should be < 4")
}
def intDynaFirst(errorFun: String, errorValue: String) =
new DynamicFirstElementTemplate("Int", errorFun, errorValue)
val int123Types =
List(
("at least one element failed", " should not equal 2", "getFirstNotEqual[Int]", "getFirstEqual[Int]", "2", (errorFun: String, errorValue: String) => new EqualedMessageTemplate(intDynaFirst(errorFun, errorValue), 2)),
("more than one element failed", " should be < 2", "getFirstLessThan", "getFirstMoreThanEqual", "2", (errorFun: String, errorValue: String) => new WasNotLessThanMessageTemplate(intDynaFirst(errorFun, errorValue), 2))
) ++ stdInt123Types(intDynaFirst, 2, "getFirst")
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
def stringDynaFirst(errorFun: String, errorValue: String) =
new DynamicFirstElementTemplate("String", errorFun, errorValue)
def stringDynaFirstLength(errorFun: String, errorValue: String) =
new DynamicFirstElementLengthTemplate("String", errorFun, errorValue)
val nullStringTypes = stdNullStringTypes(stringDynaFirst, "getFirst")
val propertyCheckCol = genCol("\"\", \"boom!\", \"\"", "\"Array(, boom!, )\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, stringDynaFirst, stringDynaFirst, stringDynaFirstLength, "getFirst")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, stringDynaFirst, stringDynaFirstLength, "getFirst")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(stringDynaFirst, "2", "getFirst")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(stringDynaFirst, "getFirst")
def trvStringDynaFirst(colType: String, errorFun: String, errorValue: String) =
if (colType.startsWith("Array"))
new DynamicFirstArrayElementTemplate(colType, errorFun, errorValue)
else
new DynamicFirstElementTemplate(colType, errorFun, errorValue)
def trvStringDynaFirstLength(colType: String, errorFun: String, errorValue: String) =
new DynamicFirstElementLengthTemplate(colType, errorFun, errorValue)
def trvStringDynaFirstSize(colType: String, errorFun: String, errorValue: String) =
new DynamicFirstElementSizeTemplate(colType, errorFun, errorValue)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvStringDynaFirst, "getFirst").filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvStringDynaFirst, trvStringDynaFirstSize, 0, 1, "hi", "getFirst")
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(intDynaFirst, '2', "getFirst", true, false)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(intDynaFirst, (2, 2), "getFirst")
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(intDynaFirst, (2, 2), "getFirst", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvStringDynaFirst, "getFirst")
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvStringDynaFirst, trvStringDynaFirstSize, "getFirst")
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvStringDynaFirst, trvStringDynaFirstSize, "getFirst")
val allColText = "all(xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "Int", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "String", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
})++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "String", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "String", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "String", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
(colText, condition, allColText + assertText, colType, okFun, errorFun, errorValue, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
(colText, condition, allColText + assertText, colType, okFun, errorFun, errorValue, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
(colText, condition, allColText + assertText, colType, okFun, errorFun, errorValue, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "Char", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "Int", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
(colText, condition, allColText + assertText, "Int", okFun, errorFun, errorValue, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
(colText, condition, allColText + assertText, colType, okFun, errorFun, errorValue, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
(colText, condition, allColText + assertText, colType, okFun, errorFun, errorValue, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
genFile(
new File(targetDir, "InspectorShorthandsForAllSucceededSpec.scala"),
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.all"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForAllSucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForAllFailedSpec" + i
val inspectorShorthandsForAllFailedSpecFile = new File(targetDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForAllErrorTemplateWithCause(colText, condition, assertText, inspectorShorthandsForAllFailedSpecFile.getName,
colType, errorFun, errorValue, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForAllFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.all"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForAtLeastSpecFile(targetDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
(int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("atLeast(2, " + colText + ")", "elements succeeded count is equal to the min", "atLeast(2, " + colText + ") should be < 3")
})
val inspectorShorthandsForAtLeastSucceededSpecFile = new File(targetDir, "InspectorShorthandsForAtLeastSucceededSpec.scala")
genFile(
inspectorShorthandsForAtLeastSucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.atLeast"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForAtLeastSucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("at least one element failed", " should equal (2)", "indexElementEqual[Int]", "indexElementNotEqual[Int]", "2", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate("{1}", 2, false))
) ++ stdInt123Types(simpleMessageFun, 2, "indexElement", false)
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false)
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\"", "\"Array(, boom!, hi)\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 0, 1, "hi", "indexElement", true)
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(simpleMessageFun, '2', "indexElement", true, true)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val atLeast2ColText = "atLeast(3, xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "2")
val passedCount = 3 - List("1", "2", "3").filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, errorValue)
val passedCount = 3 - List("hello A!", "hi B", "hello C!").filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getSizeFun(errorFun, 0)
val passedCount = 3 - List("hi", "boom!", "").filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getTraversableFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List("hello")).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val errorAssertFun = getMapFun(errorFun, right)
val passedCount = 3 - List(Map("1" -> "one", "2" -> "two", "3" -> "three"),
Map("4" -> "four", "5" -> "five", "6" -> "six"),
Map("2" -> "two", "6" -> "six", "8" -> "eight")).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val errorAssertFun = getJavaColFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List.empty[String]).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val errorAssertFun = getJavaMapFun(errorFun, right)
import collection.JavaConversions._
val passedCount = 3 - List[java.util.Map[String, String]](Map.empty[String, String],
Map("b" -> "boom!"),
Map("h" -> "hello!")).filter(errorAssertFun).length
(colText, condition, atLeast2ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForAtLeastFailedSpec" + i
val inspectorShorthandsForAtLeastFailedSpecFile = new File(targetDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForAtLeastErrorTemplate(colText, condition, assertText, inspectorShorthandsForAtLeastFailedSpecFile.getName,
colType, errorFun, errorValue, 3, 3, passedCount, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForAtLeastFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.atLeast"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForEverySpecFile(targetMatchersDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("every(" + colText + ")", "all elements succeeded", "every(" + colText + ") should be < 4")
}
val inspectorShorthandsForEverySucceededSpecFile = new File(targetMatchersDir, "InspectorShorthandsForEverySucceededSpec.scala")
genFile(
inspectorShorthandsForEverySucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.every"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForEverySucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("at least one element failed", " should not equal 2", "indexElementNotEqual[Int]", "indexElementEqual[Int]", "2", (errorFun: String, errorValue: String) => new EqualedMessageTemplate("{1}", 2, false)),
("more than one element failed", " should be < 2", "indexElementLessThan", "indexElementMoreThanEqual", "2", (errorFun: String, errorValue: String) => new WasNotLessThanMessageTemplate("{1}", 2, false))
) ++ stdInt123Types(simpleMessageFun, 2, "indexElement", false)
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false)
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\"", "\"Array(, boom!, hi)\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 0, 1, "hi", "indexElement", true)
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(simpleMessageFun, '2', "indexElement", true, true)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val everyColText = "every(xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "2")
val passedCount = 3 - List("1", "2", "3").filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, errorValue)
val passedCount = 3 - List("hello A!", "hi B", "hello C!").filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getSizeFun(errorFun, 0)
val passedCount = 3 - List("hi", "boom!", "").filter(errorAssertFun).length
(colText, condition, everyColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getTraversableFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List("hello")).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val errorAssertFun = getMapFun(errorFun, right)
val passedCount = 3 - List(Map("1" -> "one", "2" -> "two", "3" -> "three"),
Map("4" -> "four", "5" -> "five", "6" -> "six"),
Map("2" -> "two", "6" -> "six", "8" -> "eight")).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val errorAssertFun = getJavaColFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List.empty[String]).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val errorAssertFun = getJavaMapFun(errorFun, right)
import collection.JavaConversions._
val passedCount = 3 - List[java.util.Map[String, String]](Map.empty[String, String],
Map("b" -> "boom!"),
Map("h" -> "hello!")).filter(errorAssertFun).length
(colText, condition, everyColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForEveryFailedSpec" + i
val inspectorShorthandsForEveryFailedSpecFile = new File(targetMatchersDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForEveryErrorTemplate(colText, condition, assertText, inspectorShorthandsForEveryFailedSpecFile.getName,
colType, errorFun, errorValue, 3, passedCount, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForEveryFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.every"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForExactlySpecFile(targetMatchersDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
(int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("atLeast(2, " + colText + ")", "elements succeeded count is exactly the same as specified", "exactly(3, " + colText + ") should be < 4")
})
val inspectorShorthandsForExactlySucceededSpecFile = new File(targetMatchersDir, "InspectorShorthandsForExactlySucceededSpec.scala")
genFile(
inspectorShorthandsForExactlySucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.exactly"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForExactlySucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("less one element passed", " should equal (2)", "Equal[Int]", "indexElementNotEqual[Int]", "2", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate("{1}", 2, false))
) ++ stdInt123Types(simpleMessageFun, 2, "indexElement", false)
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false)
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\"", "\"Array(, boom!, hi)\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 0, 1, "hi", "indexElement", true)
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(simpleMessageFun, '2', "indexElement", true, true)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val exactly3ColText = "exactly(3, xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "2")
val passedCount = 3 - List("1", "2", "3").filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, errorValue)
val passedCount = 3 - List("hello A!", "hi B", "hello C!").filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getSizeFun(errorFun, 0)
val passedCount = 3 - List("hi", "boom!", "").filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getTraversableFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List("hello")).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val errorAssertFun = getMapFun(errorFun, right)
val passedCount = 3 - List(Map("1" -> "one", "2" -> "two", "3" -> "three"),
Map("4" -> "four", "5" -> "five", "6" -> "six"),
Map("2" -> "two", "6" -> "six", "8" -> "eight")).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val errorAssertFun = getJavaColFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List.empty[String]).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val errorAssertFun = getJavaMapFun(errorFun, right)
import collection.JavaConversions._
val passedCount = 3 - List[java.util.Map[String, String]](Map.empty[String, String],
Map("b" -> "boom!"),
Map("h" -> "hello!")).filter(errorAssertFun).length
(colText, condition, exactly3ColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForExactlyFailedSpec" + i
val inspectorShorthandsForExactlyFailedSpecFile = new File(targetMatchersDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForExactlyErrorTemplate(colText, condition, assertText, inspectorShorthandsForExactlyFailedSpecFile.getName,
colType, okFun, errorFun, errorValue, 3, 3, passedCount, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForExactlyFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.exactly"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForNoSpecFile(targetMatchersDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("no(" + colText + ")", "no elements succeeded", "every(" + colText + ") should be > 0")
}
val inspectorShorthandsForNoSucceededSpecFile = new File(targetMatchersDir, "InspectorShorthandsForNoSucceededSpec.scala")
genFile(
inspectorShorthandsForNoSucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.no"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForNoSucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("at least one element failed", " should equal (2)", "Equal[Int]", "indexElementNotEqual[Int]", "2", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate("{1}", 2, false))
) ++ stdInt123Types(simpleMessageFun, 2, "indexElement", false)
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false)
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\"", "\"Array(, boom!, hi)\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 1, 2, "hi", "indexElement", true)
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(simpleMessageFun, '2', "indexElement", true, true)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val noColText = "no(xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, noColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, noColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, noColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, noColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "2")
val passedCount = 3 - List("1", "2", "3").filter(errorAssertFun).length
(colText, condition, noColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, errorValue)
val passedCount = 3 - List("hello A!", "hi B", "hello C!").filter(errorAssertFun).length
(colText, condition, noColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getSizeFun(errorFun, 0)
val passedCount = 3 - List("hi", "boom!", "").filter(errorAssertFun).length
(colText, condition, noColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getTraversableFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List("hello")).filter(errorAssertFun).length
(colText, condition, noColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, noColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, noColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, noColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val errorAssertFun = getMapFun(errorFun, right)
val passedCount = 3 - List(Map("1" -> "one", "2" -> "two", "3" -> "three"),
Map("4" -> "four", "5" -> "five", "6" -> "six"),
Map("2" -> "two", "6" -> "six", "8" -> "eight")).filter(errorAssertFun).length
(colText, condition, noColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val errorAssertFun = getJavaColFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List.empty[String]).filter(errorAssertFun).length
(colText, condition, noColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val errorAssertFun = getJavaMapFun(errorFun, right)
import collection.JavaConversions._
val passedCount = 3 - List[java.util.Map[String, String]](Map.empty[String, String],
Map("b" -> "boom!"),
Map("h" -> "hello!")).filter(errorAssertFun).length
(colText, condition, noColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForNoFailedSpec" + i
val inspectorShorthandsForNoFailedSpecFile = new File(targetMatchersDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForNoErrorTemplate(colText, condition, assertText, inspectorShorthandsForNoFailedSpecFile.getName,
colType, okFun, errorFun, errorValue, xsText, useIndex)
}
genFile(
inspectorShorthandsForNoFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.no"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForBetweenSpecFile(targetMatchersDir: File) {
val int123Col = genCol("1, 2, 3", "\"Array(1, 2, 3)\"")
val succeedTests =
int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("between(2, 4, " + colText + ")", "elements succeeded count is in range", "between(2, 4, " + colText + ") should be > 0")
}
val inspectorShorthandsForBetweenSucceededSpecFile = new File(targetMatchersDir, "InspectorShorthandsForBetweenSucceededSpec.scala")
genFile(
inspectorShorthandsForBetweenSucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.between"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForBetweenSucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("less one element passed", " should equal (2)", "Equal[Int]", "indexElementNotEqual[Int]", "2", (errorFun: String, errorValue: String) => new DidNotEqualMessageTemplate("{1}", 2, false))
) ++ stdInt123Types(simpleMessageFun, 2, "indexElement", false)
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false)
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\"", "\"Array(, boom!, hi)\"")
val propertyCheckTypes = stdPropertyCheckTypes(0, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement")
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(0, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\"", "\"Array(1, 2, 3)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement")
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\"", "\"Array(hello A!, hi B, hello C!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", ""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array())\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
// XXX
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 0, 1, "hi", "indexElement", true)
val stringCol = ("\"123\"", "xs")
val stringTypes = stdStringTypes(simpleMessageFun, '2', "indexElement", true, true)
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (2, 2), "indexElement", false)
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(0, 1, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true)
val betweenColText = "between(7, 8, xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "")
val passedCount = 3 - List("", "boom!", "hi").filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, "2")
val passedCount = 3 - List("1", "2", "3").filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, errorValue)
val passedCount = 3 - List("hello A!", "hi B", "hello C!").filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getSizeFun(errorFun, 0)
val passedCount = 3 - List("hi", "boom!", "").filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val errorAssertFun = getTraversableFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List("hello")).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val errorAssertFun = getFun(errorFun, 2)
val passedCount = 3 - List(1, 2, 3).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val errorAssertFun = getMapFun(errorFun, right)
val passedCount = 3 - List(Map("1" -> "one", "2" -> "two", "3" -> "three"),
Map("4" -> "four", "5" -> "five", "6" -> "six"),
Map("2" -> "two", "6" -> "six", "8" -> "eight")).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val errorAssertFun = getJavaColFun(errorFun, right)
val passedCount = 3 - List(List("hi"), List("boom!"), List.empty[String]).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val errorAssertFun = getJavaMapFun(errorFun, right)
import collection.JavaConversions._
val passedCount = 3 - List[java.util.Map[String, String]](Map.empty[String, String],
Map("b" -> "boom!"),
Map("h" -> "hello!")).filter(errorAssertFun).length
(colText, condition, betweenColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForBetweenFailedSpec" + i
val inspectorShorthandsForBetweenFailedSpecFile = new File(targetMatchersDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForBetweenErrorTemplate(colText, condition, assertText, inspectorShorthandsForBetweenFailedSpecFile.getName,
colType, okFun, errorFun, errorValue, 7, 8, 3, passedCount, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForBetweenFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.between"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def genInspectorShorthandsForAtMostSpecFile(targetMatchersDir: File) {
val int123Col = genCol("1, 2, 3, 4, 5", "\"Array(1, 2, 3, 4, 5)\"")
val succeedTests =
(int123Col map { case (colText, xsText) =>
new InspectorShorthandsSucceedTemplate("atMost(5, " + colText + ")", "elements succeeded count is equal to the max", "atMost(5, " + colText + ") should be < 5")
})
val inspectorShorthandsForAtMostSucceededSpecFile = new File(targetMatchersDir, "InspectorShorthandsForAtMostSucceededSpec.scala")
genFile(
inspectorShorthandsForAtMostSucceededSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.atMost"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = "InspectorShorthandsForAtMostSucceededSpec"
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = succeedTests
}
)
)
val int123Types =
List(
("more than max element succeeded", " should not equal (2)", "NotEqual[Int]", "indexElementEqual[Int]", "2", (errorFun: String, errorValue: String) => new EqualedMessageTemplate("{1}", 2, false))
) ++
(stdInt123Types(simpleMessageFun, 3, "indexElement", false).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should equal' failed" &&
condition != "'should be' failed"
})
val nullStringCol = genNullableCol("\"1\", null, \"3\"", "\"Array(1, null, 3)\"")
val nullStringTypes = stdNullStringTypes(quotedSimpleMessageFun, "indexElement", false).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should be null' failed"
}
val propertyCheckCol = genCol("\"\", \"boom!\", \"hi\", \"cool!\", \"great!\"", "\"Array(, boom!, hi, cool!, great!)\"")
val propertyCheckTypes = stdPropertyCheckTypes(5, quotedSimpleMessageFun, quotedSimpleMessageFun2, simpleMessageFun, "indexElement").filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should be symbol' failed" &&
condition != "'should be property' failed" &&
condition != "'should be a symbol' failed" &&
condition != "'should be a property' failed" &&
condition != "'should be an symbol' failed" &&
condition != "'should be an property' failed" &&
condition != "'should have property' failed"
}
val lengthSizeCheckTypes = stdLengthSizeCheckTypes(5, quotedSimpleMessageFun, lengthSimpleMessageFun, "indexElement")
val instanceCheckCol = genCol("\"1\", theInstance, \"3\", \"4\", \"5\"", "\"Array(1, 2, 3, 4, 5)\"")
val instanceCheckTypes = stdInstanceCheckTypes(quotedSimpleMessageFun, "2", "indexElement").filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should be theSameInstanceAs' failed"
}
val stringCheckCol = genCol("\"hello A!\", \"hi B\", \"hello C!\", \"hi D\", \"hello E!\"", "\"Array(hello A!, hi B, hello C!, hi D, hello E!)\"")
val stringCheckTypes = stdStringCheckTypes(quotedSimpleMessageFun, "indexElement", true)
val traversablePropertyCheckCol = genColCol("String", Array("\"\", \"boom!\", \"great!\"", "", "\"hi\", \"cool!\""), "\"Array(Array(), Array(\\\"boom!\\\"), Array(\\\"hi\\\"), Array(\\\"cool!\\\"), Array(\\\"great!\\\"))\"")
val traversablePropertyCheckTypes = stdTraversablePropertyCheckTypes(trvSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'traversable should be symbol' failed"
}
val traversableCheckCol = genColCol("String", Array("\"hi\"", "\"boom!\"", "\"hello\"", "\"boom!\", \"hi\""), "\"Array(Array(\\\"hi\\\"), Array(\\\"boom!\\\"), Array(\\\"hello\\\"))\"")
val traversableCheckTypes = stdTraversableCheckTypes(trvSimpleMessageFun, trvSizeSimpleMessageFun, 1, 2, "hi", "indexElement", true)
val stringCol = ("\"12345\"", "xs")
val stringTypes =
stdStringTypes(simpleMessageFun, '3', "indexElement", true, true).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should equal' failed" &&
condition != "'should be' failed"
}
val numberMap = genMap(Array("1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4, 5 -> 5"))
val numberMapTypes =
stdNumberMapTypes(simpleMessageFun, (3, 3), "indexElement", false).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should equal' failed" &&
condition != "'should be' failed"
}
val numberJavaMap = genJavaMap(Array("Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4, 5 -> 5)"), "Int", "Int")
val numberJavaMapTypes =
stdNumberJavaMapTypes(simpleMessageFun, (3, 3), "indexElement", false).filter { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
condition != "'should equal' failed" &&
condition != "'should be' failed"
}
val maps = genMap(Array("\"1\" -> \"one\", \"2\" -> \"two\", \"3\" -> \"three\"",
"\"4\" -> \"four\", \"5\" -> \"five\", \"6\" -> \"six\"",
"\"2\" -> \"two\", \"6\" -> \"six\", \"8\" -> \"eight\"",
"\"7\" -> \"seven\", \"8\" -> \"eight\", \"9\" -> \"nine\""))
val mapCheckCol =
maps flatMap { case (mapText, xsText) =>
genColMap(mapText, xsText)
}
val mapCheckTypes = stdMapCheckTypes(trvSimpleMessageFun, "indexElement", true)
val javaCols = genJavaCol(Array("List(\"hi\")", "List(\"boom!\")", "List.empty[String]", "List(\"great!\")", "List(\"hi\", \"cool!\")"))
val javaColCheckCol =
javaCols flatMap { case (mapText, xsText) =>
genJavaColMap(mapText, xsText)
}
val javaColCheckTypes = stdJavaColCheckTypes(1, 0, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
condition != "'java collection should be symbol' failed"
}
val javaMaps = genJavaMap(Array("Map.empty[String, String]", "Map(\"b\" -> \"boom!\")", "Map(\"h\" -> \"hello!\")", "Map.empty[String, String]", "Map(\"b\" -> \"hello!\")", "Map(\"h\" -> \"boom!\")"), "String", "String")
val javaMapCheckCol =
javaMaps flatMap { case (mapText, xsText, colType) =>
genJavaColMap(mapText, xsText).map { case (colText, xsText) =>
(colText, xsText, colType)
}
}
val javaMapCheckTypes = stdJavaMapCheckTypes(1, 0, trvSimpleMessageFun, trvSizeSimpleMessageFun, "indexElement", true).filter { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
condition != "'java map should be symbol' failed"
}
val atMostColText = "atMost(1, xs)"
val failedTestConfigs =
(int123Col flatMap { case (colText, xsText) =>
int123Types map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2 // always 2 as atMost will fail early
(colText, condition, atMostColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(nullStringCol flatMap { case (colText, xsText) =>
nullStringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
propertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(propertyCheckCol flatMap { case (colText, xsText) =>
lengthSizeCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
(instanceCheckCol flatMap { case (colText, xsText) =>
instanceCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "String", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(stringCheckCol flatMap { case (colText, xsText) =>
stringCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "String", okFun, errorFun, "\"" + errorValue + "\"", passedCount, messageFun(errorFun, "\"" + errorValue + "\"").toString, xsText, true)
}
}) ++
(traversablePropertyCheckCol flatMap { case (colText, xsText) =>
traversablePropertyCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val passedCount = 2
(colText, condition, atMostColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterArraySymbol(colText, condition) } ++
(traversableCheckCol flatMap { case (colText, xsText) =>
traversableCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = if (colText.startsWith("Array")) "Array[String]" else "GenTraversable[String]"
val passedCount = 2
(colText, condition, atMostColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterSetLength(colText, condition) } ++
({
val (colText, xsText) = stringCol
stringTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "Char", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, true)
}
}) ++
(numberMap flatMap { case (colText, xsText) =>
numberMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(numberJavaMap flatMap { case (colText, xsText, colType) =>
numberJavaMapTypes map { case (condition, assertText, okFun, errorFun, errorValue, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, "Int", okFun, errorFun, errorValue, passedCount, messageFun(errorFun, errorValue).toString, xsText, false)
}
}) ++
(mapCheckCol flatMap { case (colText, xsText) =>
mapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "GenMap[String, String]"
val passedCount = 2
(colText, condition, atMostColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}) ++
(javaColCheckCol flatMap { case (colText, xsText) =>
javaColCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val colType = "java.util.Collection[String]"
val passedCount = 2
(colText, condition, atMostColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaColLength(colText, condition) } ++
(javaMapCheckCol flatMap { case (colText, xsText, colType) =>
javaMapCheckTypes map { case (condition, assertText, okFun, errorFun, errorValue, right, messageFun) =>
val passedCount = 2
(colText, condition, atMostColText + assertText, colType, okFun, errorFun, errorValue, passedCount, messageFun(colType, errorFun, errorValue).toString, xsText, true)
}
}).filter { case (colText, condition, _, _, _, _, _, _, _, _, _) => filterJavaMapLength(colText, condition) }
failedTestConfigs.grouped(500).toList.zipWithIndex foreach { case (configs, i) =>
val className = "InspectorShorthandsForAtMostFailedSpec" + i
val inspectorShorthandsForAtMostFailedSpecFile = new File(targetMatchersDir, className + ".scala")
val failedTests = configs map { case (colText, condition, assertText, colType, okFun, errorFun, errorValue, passedCount, causeErrMsg, xsText, useIndex) =>
new InspectorShorthandsForAtMostErrorTemplate(colText, condition, assertText, inspectorShorthandsForAtMostFailedSpecFile.getName,
colType, okFun, errorFun, errorValue, 1, passedCount, causeErrMsg, xsText, useIndex)
}
genFile(
inspectorShorthandsForAtMostFailedSpecFile,
new SingleClassFile(
packageName = Some("org.scalatest.inspectors.atMost"),
importList = List(
"org.scalatest._",
"org.scalactic.Every",
"SharedHelpers._",
"FailureMessages.decorateToStringValue",
"org.scalatest.matchers.{BePropertyMatcher, BePropertyMatchResult, HavePropertyMatcher, HavePropertyMatchResult}",
"collection.GenTraversable",
"collection.GenMap"
),
classTemplate = new ClassTemplate {
val name = className
override val extendName = Some("Spec")
override val withList = List("Matchers")
override val children = new InspectorShorthandsHelpersTemplate :: failedTests
}
)
)
}
}
def targetDir(targetBaseDir: File, packageName: String): File = {
val targetDir = new File(targetBaseDir, "org/scalatest/inspectors-shorthands/" + packageName)
if (!targetDir.exists)
targetDir.mkdirs()
targetDir
}
def genTest(targetBaseDir: File, version: String, scalaVersion: String)
}
object GenInspectorsShorthands1 extends GenInspectorsShorthandsBase {
def genTest(targetBaseDir: File, version: String, scalaVersion: String) {
genInspectorShorthandsForAllSpecFile(targetDir(targetBaseDir, "all"))
genInspectorShorthandsForAtLeastSpecFile(targetDir(targetBaseDir, "atLeast"))
genInspectorShorthandsForEverySpecFile(targetDir(targetBaseDir, "every"))
genInspectorShorthandsForExactlySpecFile(targetDir(targetBaseDir, "exactly"))
}
}
object GenInspectorsShorthands2 extends GenInspectorsShorthandsBase {
def genTest(targetBaseDir: File, version: String, scalaVersion: String) {
genInspectorShorthandsForNoSpecFile(targetDir(targetBaseDir, "no"))
genInspectorShorthandsForBetweenSpecFile(targetDir(targetBaseDir, "between"))
genInspectorShorthandsForAtMostSpecFile(targetDir(targetBaseDir, "atMost"))
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/laws/Laws.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.scalatest._
import org.scalactic._
import Matchers._
import scala.language.higherKinds
/**
* A law is a requirement expressed in the form of an assertion function
* augmented with explanatory information. As generalized, laws take no
* parameters, but are rather designed to be used where required parameters
* are in scope. Commonly, this will be a class that takes implicit generators
* for any required parameters.
*/
case class Law(lawsName: String, lawName: String, fun: () => Unit)
/**
* A Laws class represents a list of Laws, together with a name
* for the group and methods to assert all of the laws.
* @param lawsName The name of the group of laws.
*/
abstract class Laws(val lawsName: String) {
def laws: Every[Law]
def law(name: String)(code: () => Unit): Law = Law(lawsName, name, code)
def assert() = laws.foreach { law =>
withClue(s"The ${law.lawsName} ${law.lawName} law could not be verified: ")(law.fun())
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/PropertyFunSuite.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 Matchers._
class PropertyFunSuite extends FunSuite {
test("object has no appropriately named field, method, or get method (0, 0, 0)") {
class DontGotNuthin
val dgn = new DontGotNuthin
val result: Option[Any] = MatchersHelper.accessProperty(dgn, 'fred, false)
result should be (None)
}
test("object has only an appropriately named get method (0, 0, 1)") {
class HasGetMethod {
def getCow: Int = 1
}
val obj = new HasGetMethod
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has only an appropriately named Boolean is method (0, 0, 1)") {
class HasIsMethod {
def isCow: Boolean = true
}
val obj = new HasIsMethod
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, true)
result should be (Some(true))
}
test("object has only an appropriately named method (0, 1, 0)") {
class HasMethod {
def cow: Int = 1
}
val obj = new HasMethod
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has only an appropriately named Scala field, which results in a Java method (0, 1, 0)") {
class HasScalaField {
val cow: Int = 1
}
val obj = new HasScalaField
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has only an appropriately named method and getMethod (0, 1, 1)") {
class HasMethod {
def cow: Int = 1
def getCow: Int = 2
}
val obj = new HasMethod
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has only an appropriately named field (1, 0, 0)") {
val obj = new HasField // A Java class, because can't get a field in a Scala class
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has an appropriately named field and getMethod (1, 0, 1)") {
val obj = new HasFieldAndGetMethod // A Java class, because can't get a field in a Scala class
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has an appropriately named field and method (1, 1, 0)") {
val obj = new HasFieldAndMethod // A Java class, because can't get a field in a Scala class
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("object has an appropriately named field and method and getMethod (1, 1, 1)") {
val obj = new HasFieldMethodAndGetMethod // A Java class, because can't get a field in a Scala class
val result: Option[Any] = MatchersHelper.accessProperty(obj, 'cow, false)
result should be (Some(1))
}
test("works on set.empty") {
val result1: Option[Any] = MatchersHelper.accessProperty(Set(), 'empty, true)
result1 should be (Some(true))
val result2: Option[Any] = MatchersHelper.accessProperty(Set(1, 2, 3), 'empty, true)
result2 should be (Some(false))
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldMatchPatternSpec.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 OptionValues._
import org.scalactic.Prettifier
import SharedHelpers.thisLineNumber
import Matchers._
import exceptions.TestFailedException
class ShouldMatchPatternSpec extends FunSpec with OptionValues {
case class Person(firstName: String, lastName: String)
val result = Person("Bob", "Mc")
val result2 = Person("Alice", "Ms")
def didNotMatchTheGivenPattern(left: Any): String =
Prettifier.default(left) + " did not match the given pattern"
def matchedTheGivenPattern(left: Any): String =
Prettifier.default(left) + " matched the given pattern"
def equaled(left: Any, right: Any): String =
FailureMessages.equaled(left, right)
def didNotEqual(left: Any, right: Any): String =
FailureMessages.didNotEqual(left, right)
def wasEqualTo(left: Any, right: Any): String =
FailureMessages.wasEqualTo(left, right)
def wasNotEqualTo(left: Any, right: Any): String =
FailureMessages.wasNotEqualTo(left, right)
describe("should matchPattern syntax") {
it("should do nothing when checking the right pattern") {
result should matchPattern { case Person("Bob", _) => }
}
it("should throw TestFailedException with correct error message when checking wrong pattern") {
val e = intercept[TestFailedException] {
result should matchPattern { case Person("Alice", _) => }
}
e.message.value shouldBe didNotMatchTheGivenPattern(result)
e.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile when RHS of case definition is not empty") {
("Person(\"Bob\", \"Mc\") should matchPattern { case Person(\"Bob\", last) =>\n" +
" last should startWith(\"Mc\")\n" +
"}") shouldNot compile
}
it("should do nothing if pattern matches and used in a logical-and expression") {
result should (matchPattern { case Person("Bob", _) => } and (equal (result)))
result should (equal (result) and (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } and equal (result))
result should (equal (result) and matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } and (be (result)))
result should (be (result) and (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } and be (result))
result should (be (result) and matchPattern { case Person("Bob", _) => })
}
it("should throw TFE with correct stack depth if pattern does not match and used in a logical-and expression") {
val e1 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } and (equal (result)))
}
e1.message should be (Some(didNotMatchTheGivenPattern(result)))
e1.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
result should (equal (result) and (matchPattern { case Person("Alice", _) => }))
}
e2.message should be (Some(equaled(result, result) + ", but " + didNotMatchTheGivenPattern(result)))
e2.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } and equal (result))
}
e3.message should be (Some(didNotMatchTheGivenPattern(result)))
e3.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
result should (equal (result) and matchPattern { case Person("Alice", _) => })
}
e4.message should be (Some(equaled(result, result) + ", but " + didNotMatchTheGivenPattern(result)))
e4.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } and (be (result)))
}
e5.message should be (Some(didNotMatchTheGivenPattern(result)))
e5.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
result should (be (result) and (matchPattern { case Person("Alice", _) => }))
}
e6.message should be (Some(wasEqualTo(result, result) + ", but " + didNotMatchTheGivenPattern(result)))
e6.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } and be (result))
}
e7.message should be (Some(didNotMatchTheGivenPattern(result)))
e7.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
result should (be (result) and matchPattern { case Person("Alice", _) => })
}
e8.message should be (Some(wasEqualTo(result, result) + ", but " + didNotMatchTheGivenPattern(result)))
e8.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile if RHS of case definition is not empty and used in a logical-and expression") {
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } and (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) and (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } and equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) and matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } and (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) and (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } and be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) and matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
}
it("should do nothing if pattern matches and used in a logical-or expression") {
result should (matchPattern { case Person("Bob", _) => } or (equal (result)))
result should (equal (result) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or equal (result))
result should (equal (result) or matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } or (be (result)))
result should (be (result) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or be (result))
result should (be (result) or matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } or (equal (result)))
result should (equal (result) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or equal (result))
result should (equal (result) or matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } or (be (result)))
result should (be (result) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or be (result))
result should (be (result) or matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } or (equal (result2)))
result should (equal (result2) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or equal (result2))
result should (equal (result2) or matchPattern { case Person("Bob", _) => })
result should (matchPattern { case Person("Bob", _) => } or (be (result2)))
result should (be (result2) or (matchPattern { case Person("Bob", _) => }))
result should (matchPattern { case Person("Bob", _) => } or be (result2))
result should (be (result2) or matchPattern { case Person("Bob", _) => })
}
it("should throw TFE with correct stack depth if pattern does not match and used in a logical-or expression") {
val e1 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } or (equal (result2)))
}
e1.message should be (Some(didNotMatchTheGivenPattern(result) + ", and " + didNotEqual(result, result2)))
e1.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
result should (equal (result2) or (matchPattern { case Person("Alice", _) => }))
}
e2.message should be (Some(didNotEqual(result, result2) + ", and " + didNotMatchTheGivenPattern(result)))
e2.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } or equal (result2))
}
e3.message should be (Some(didNotMatchTheGivenPattern(result) + ", and " + didNotEqual(result, result2)))
e3.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
result should (equal (result2) or matchPattern { case Person("Alice", _) => })
}
e4.message should be (Some(didNotEqual(result, result2) + ", and " + didNotMatchTheGivenPattern(result)))
e4.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } or (be (result2)))
}
e5.message should be (Some(didNotMatchTheGivenPattern(result) + ", and " + wasNotEqualTo(result, result2)))
e5.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
result should (be (result2) or (matchPattern { case Person("Alice", _) => }))
}
e6.message should be (Some(wasNotEqualTo(result, result2) + ", and " + didNotMatchTheGivenPattern(result)))
e6.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
result should (matchPattern { case Person("Alice", _) => } or be (result2))
}
e7.message should be (Some(didNotMatchTheGivenPattern(result) + ", and " + wasNotEqualTo(result, result2)))
e7.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
result should (be (result2) or matchPattern { case Person("Alice", _) => })
}
e8.message should be (Some(wasNotEqualTo(result, result2) + ", and " + didNotMatchTheGivenPattern(result)))
e8.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("fail to compile if RHS of case definition is not empty and used in a logical-or expression") {
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (equal (result2)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result2) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or equal (result2))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result2) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or (be (result2)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result2) or (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") } or be (result2))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result2) or matchPattern { case Person(\"Bob\", last) => last should startWith(\"Mc\") })" shouldNot compile
}
}
describe("should not matchPattern syntax") {
it("should do nothing when checking the wrong pattern") {
result should not matchPattern { case Person("Alice", _) => }
}
it("should throw TestFailedException with correct error message when checking right pattern") {
val e = intercept[TestFailedException] {
result should not matchPattern { case Person("Bob", _) => }
}
e.message.value shouldBe matchedTheGivenPattern(result)
e.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile when RHS of case definition is not empty") {
("Person(\"Bob\", \"Mc\") should not matchPattern { case Person(\"Bob\", last) =>\n" +
" last should startWith(\"Mc\")\n" +
"}") shouldNot compile
}
it("should do nothing if pattern does not match and used in a logical-and expression and not") {
result should (not matchPattern { case Person("Alice", _) => } and (equal (result)))
result should (equal (result) and (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } and equal (result))
result should (equal (result) and not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } and (be (result)))
result should (be (result) and (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } and be (result))
result should (be (result) and not matchPattern { case Person("Alice", _) => })
}
it("should do nothing if pattern matches and used in a logical-and expression and not") {
val e1 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } and (equal (result)))
}
e1.message should be (Some(matchedTheGivenPattern(result)))
e1.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
result should (equal (result) and (not matchPattern { case Person("Bob", _) => }))
}
e2.message should be (Some(equaled(result, result) + ", but " + matchedTheGivenPattern(result)))
e2.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } and equal (result))
}
e3.message should be (Some(matchedTheGivenPattern(result)))
e3.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
result should (equal (result) and not matchPattern { case Person("Bob", _) => })
}
e4.message should be (Some(equaled(result, result) + ", but " + matchedTheGivenPattern(result)))
e4.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } and (be (result)))
}
e5.message should be (Some(matchedTheGivenPattern(result)))
e5.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
result should (be (result) and (not matchPattern { case Person("Bob", _) => }))
}
e6.message should be (Some(wasEqualTo(result, result) + ", but " + matchedTheGivenPattern(result)))
e6.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } and be (result))
}
e7.message should be (Some(matchedTheGivenPattern(result)))
e7.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
result should (be (result) and not matchPattern { case Person("Bob", _) => })
}
e8.message should be (Some(wasEqualTo(result, result) + ", but " + matchedTheGivenPattern(result)))
e8.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile if RHS of case definition is not empty and used in a logical-and expression and not") {
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } and (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) and (not matchPattern { case Person(\"Alice\", _) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } and equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) and not matchPattern { case Person(\"Alice\", _) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } and (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) and (not matchPattern { case Person(\"Alice\", _) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } and be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) and not matchPattern { case Person(\"Alice\", _) => last should startWith(\"Mc\") })" shouldNot compile
}
it("should do nothing if pattern does not match and used in a logical-or expression and not") {
result should (not matchPattern { case Person("Alice", _) => } or (equal (result)))
result should (equal (result) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or equal (result))
result should (equal (result) or not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } or (be (result)))
result should (be (result) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or be (result))
result should (be (result) or not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } or (equal (result)))
result should (equal (result) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or equal (result))
result should (equal (result) or not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } or (be (result)))
result should (be (result) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or be (result))
result should (be (result) or not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } or (equal (result2)))
result should (equal (result2) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or equal (result2))
result should (equal (result2) or not matchPattern { case Person("Alice", _) => })
result should (not matchPattern { case Person("Alice", _) => } or (be (result2)))
result should (be (result2) or (not matchPattern { case Person("Alice", _) => }))
result should (not matchPattern { case Person("Alice", _) => } or be (result2))
result should (be (result2) or not matchPattern { case Person("Alice", _) => })
}
it("should throw TFE with correct stack depth if pattern matches and used in a logical-or expression and not") {
val e1 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } or (equal (result2)))
}
e1.message should be (Some(matchedTheGivenPattern(result) + ", and " + didNotEqual(result, result2)))
e1.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
result should (equal (result2) or (not matchPattern { case Person("Bob", _) => }))
}
e2.message should be (Some(didNotEqual(result, result2) + ", and " + matchedTheGivenPattern(result)))
e2.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } or equal (result2))
}
e3.message should be (Some(matchedTheGivenPattern(result) + ", and " + didNotEqual(result, result2)))
e3.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
result should (equal (result2) or not matchPattern { case Person("Bob", _) => })
}
e4.message should be (Some(didNotEqual(result, result2) + ", and " + matchedTheGivenPattern(result)))
e4.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } or (be (result2)))
}
e5.message should be (Some(matchedTheGivenPattern(result) + ", and " + wasNotEqualTo(result, result2)))
e5.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
result should (be (result2) or (not matchPattern { case Person("Bob", _) => }))
}
e6.message should be (Some(wasNotEqualTo(result, result2) + ", and " + matchedTheGivenPattern(result)))
e6.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
result should (not matchPattern { case Person("Bob", _) => } or be (result2))
}
e7.message should be (Some(matchedTheGivenPattern(result) + ", and " + wasNotEqualTo(result, result2)))
e7.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
result should (be (result2) or not matchPattern { case Person("Bob", _) => })
}
e8.message should be (Some(wasNotEqualTo(result, result2) + ", and " + matchedTheGivenPattern(result)))
e8.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile if RHS of case definition is not empty and used in a logical-or expression and not") {
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (equal (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or equal (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (be (result)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or be (result))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (equal (result2)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result2) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or equal (result2))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (equal (result2) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or (be (result2)))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result2) or (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") }))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") } or be (result2))" shouldNot compile
"Person(\"Bob\", \"Mc\") should (be (result2) or not matchPattern { case Person(\"Alice\", last) => last should startWith(\"Mc\") })" shouldNot compile
}
}
describe("shouldNot matchPattern syntax") {
it("should do nothing when checking the wrong pattern") {
result shouldNot matchPattern { case Person("Alice", _) => }
}
it("should throw TestFailedException with correct error message when checking right pattern") {
val e = intercept[TestFailedException] {
result should not matchPattern { case Person("Bob", _) => }
}
e.message.value shouldBe matchedTheGivenPattern(result)
e.failedCodeFileName should be (Some("ShouldMatchPatternSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
it("should fail to compile when RHS of case definition is not empty") {
("result should not matchPattern { case Person(\"Bob\", last) =>\n" +
" last should startWith(\"Mc\")\n" +
"}") shouldNot compile
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/tools/SbtCommandParserSpec.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.tools
import org.scalatest.FunSpec
import org.scalatest.Matchers
class SbtCommandParserSpec extends FunSpec with Matchers {
val parser = new SbtCommandParser
def canParsePhrase(s: String) {
val result: parser.ParseResult[Any] = parser.parseResult(s)
result match {
case ns: parser.NoSuccess => fail(ns.toString)
case _ =>
}
}
def cannotParsePhrase(s: String) {
val result: parser.ParseResult[Any] = parser.parseResult(s)
result match {
case parser.Success(result, _) => fail("wasn't supposed to, but parsed: " + result)
case _ =>
}
}
describe("the cmd terminal?") {
it("should parse 'st'") {
canParsePhrase("""st""")
canParsePhrase("""st --""")
}
}
}
|
cquiroz/scalatest | scalatest.js/src/main/scala/org/scalatest/tools/ScalaTestSbtEvent.scala | <gh_stars>1-10
package org.scalatest.tools
import sbt.testing._
private[tools] case class ScalaTestSbtEvent(
fullyQualifiedName: String,
fingerprint: Fingerprint,
selector: Selector,
status: Status,
throwable: OptionalThrowable,
duration: Long) extends Event |
cquiroz/scalatest | project/GenTheyWord.scala |
import java.io.File
import java.io.BufferedWriter
import java.io.FileWriter
import scala.io.Source
object GenTheyWord {
def generateFile(srcFileDir: String, srcClassName: String, targetFileDir: String, targetClassName: String) {
val targetDir = new File(targetFileDir)
targetDir.mkdirs()
val writer = new BufferedWriter(new FileWriter(new File(targetFileDir, targetClassName + ".scala")))
try {
val itLines = Source.fromFile(new File(srcFileDir, srcClassName + ".scala")).getLines().toList // for 2.8
for (itLine <- itLines) {
//.replaceAll("\"An it clause", "\"A they clause")
//.replaceAll("an it clause", "a they clause")
val theyLine = itLine.replaceAll("\\sit\\(", " they\\(")
.replaceAll("\\sit\\s", " they ")
.replaceAll("\"it\\s", "\"they ")
.replaceAll("they or they clause.\"", "it or they clause.\"")
.replaceAll("\"An they clause", "\"A they clause")
.replaceAll("an they or a they clause.\"", "an it or a they clause.\"")
.replaceAll(srcClassName, targetClassName)
writer.write(theyLine)
writer.newLine() // add for 2.8
}
}
finally {
writer.close()
}
}
def main(args: Array[String]) {
}
def genTest(dir: File, version: String, scalaVersion: String) {
generateFile("scalatest-test/src/test/scala/org/scalatest",
"FunSpecSuite",
dir.getAbsolutePath,
"FunSpecSuiteUsingThey")
generateFile("scalatest-test/src/test/scala/org/scalatest",
"FunSpecSpec",
dir.getAbsolutePath,
"FunSpecSpecUsingThey")
generateFile("scalatest-test/src/test/scala/org/scalatest",
"FlatSpecSpec",
dir.getAbsolutePath,
"FlatSpecSpecUsingThey")
generateFile("scalatest-test/src/test/scala/org/scalatest/path",
"FunSpecSpec",
dir.getAbsolutePath,
"PathFunSpecSpecUsingThey")
generateFile("scalatest-test/src/test/scala/org/scalatest/fixture",
"FunSpecSpec",
dir.getAbsolutePath,
"FixtureFunSpecSpecUsingThey")
generateFile("scalatest-test/src/test/scala/org/scalatest/fixture",
"FlatSpecSpec",
dir.getAbsolutePath,
"FixtureFlatSpecSpecUsingThey")
}
} |
cquiroz/scalatest | project/GenMatchers.scala | <reponame>cquiroz/scalatest
import collection.mutable.ListBuffer
import io.Source
import java.io.{File, FileWriter, BufferedWriter}
/*
* 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.
*/
object GenMatchers {
def translateShouldToMust(shouldLine: String): String = {
shouldLine
.replaceAll("Trait <a href=\"MustMatchers.html\"><code>MustMatchers</code></a> is an alternative to <code>Matchers</code>", "Trait <code>MustMatchers</code> is an alternative to <a href=\"Matchers.html\"><code>Matchers</code></a>")
.replaceAll("MustMatchers", "I_NEED_TO_STAY_MUSTMATCHERS")
.replaceAll("ShouldMatchers", "I_NEED_TO_STAY_SHOULDMATCHERS")
.replaceAll("must", "I_NEED_TO_STAY_SMALL_MUST")
.replaceAll("Must", "I_NEED_TO_STAY_BIG_MUST")
.replaceAll("<!-- PRESERVE --><code>should", "<code>I_NEED_TO_STAY_SMALL_SHOULD")
.replaceAll("<!-- PRESERVE -->should", " I_NEED_TO_STAY_SMALL_SHOULD") // Why is there a space in front?
.replaceAll("should", "must")
.replaceAll("Should", "Must")
.replaceAll("trait Matchers", "trait MustMatchers")
.replaceAll("object Matchers extends Matchers", "object MustMatchers extends MustMatchers")
.replaceAll("I_NEED_TO_STAY_SMALL_SHOULD", "should")
.replaceAll("I_NEED_TO_STAY_BIG_MUST", "Must")
.replaceAll("I_NEED_TO_STAY_SMALL_MUST", "must")
.replaceAll("I_NEED_TO_STAY_SHOULDMATCHERS", "ShouldMatchers")
.replaceAll("I_NEED_TO_STAY_MUSTMATCHERS", "MustMatchers")
.replaceAll("import Matchers._", "import MustMatchers._")
.replaceAll("import org.scalatest.Matchers._", "import org.scalatest.MustMatchers._")
.replaceAll("Matchers.scala", "MustMatchers.scala")
}
def genMain(targetDir: File, version: String, scalaVersion: String) {
targetDir.mkdirs()
val matchersDir = new File(targetDir, "matchers")
matchersDir.mkdirs()
val junitDir = new File(targetDir, "junit")
junitDir.mkdirs()
val mustMatchersFile = new File(targetDir, "MustMatchers.scala")
val mustMatchersWriter = new BufferedWriter(new FileWriter(mustMatchersFile))
try {
val lines = Source.fromFile(new File("scalatest/src/main/scala/org/scalatest/Matchers.scala")).getLines.toList
for (line <- lines) {
val mustLine = translateShouldToMust(line)
mustMatchersWriter.write(mustLine)
mustMatchersWriter.newLine()
}
}
finally {
mustMatchersWriter.flush()
mustMatchersWriter.close()
println("Generated " + mustMatchersFile.getAbsolutePath)
}
val deprecatedMustMatchers = """
| package org.scalatest.matchers
|
| @deprecated("Please use org.scalatest.MustMatchers instead.")
| trait MustMatchers extends org.scalatest.MustMatchers
|
| @deprecated("Please use org.scalatest.MustMatchers instead.")
| object MustMatchers extends org.scalatest.MustMatchers
""".stripMargin
val deprecatedMustMatchersFile = new File(matchersDir, "MustMatchers.scala")
val deprecatedMustMatchersWriter = new BufferedWriter(new FileWriter(deprecatedMustMatchersFile))
try {
deprecatedMustMatchersWriter.write(deprecatedMustMatchers)
}
finally {
deprecatedMustMatchersWriter.flush()
deprecatedMustMatchersWriter.close()
println("Generated " + deprecatedMustMatchersFile.getAbsolutePath)
}
/*
val matchersPackageObject = """
| package org.scalatest
|
| package object matchers {
|
| /**
| * Convenience type alias allowing <code>MustMatchers</code> to be used in <code>matchers</code> without qualification or another import
| * after a wildcard import of <code>org.scalatest</code>.
| */
|
| /**
| * <p>
| * <strong>This class has been moved to the <code>org.scalatest</code> package. The deprecated type alias that has been left in its place will
| * be removed in a future version of ScalaTest. Please change any uses of <code>org.scalatest.matchers.MustMatchers</code> to <code>org.scalatest.MustMatchers</code>.</strong>
| * </p>
| */
| @deprecated("Please use org.scalatest.MustMatchers instead.")
| type MustMatchers = org.scalatest.MustMatchers
| }
""".stripMargin
val matchersPackageObjectFile = new File(matchersDir, "package.scala")
val matchersPackageObjectWriter = new BufferedWriter(new FileWriter(matchersPackageObjectFile))
try {
matchersPackageObjectWriter.write(matchersPackageObject)
}
finally {
matchersPackageObjectWriter.flush()
matchersPackageObjectWriter.close()
println("Generated " + matchersPackageObjectFile.getAbsolutePath)
}
*/
}
}
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/SortedEquaMapSpec.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
class SortedEquaMapSpec extends UnitSpec {
implicit class HasExactType[T](o: T) {
def shouldHaveExactType[U](implicit ev: T =:= U): Unit = ()
}
val lower = SortedEquaPath[String](StringNormalizations.lowerCased.toOrderingEquality)
"An SortedEquaMap" can "be constructed with empty" in {
val emptyMap = lower.SortedEquaMap.empty
emptyMap shouldBe empty
val treeEmptyMap = lower.TreeEquaMap.empty
treeEmptyMap shouldBe empty
lower.SortedEquaSet.empty.shouldHaveExactType[lower.SortedEquaSet]
lower.TreeEquaSet.empty.shouldHaveExactType[lower.TreeEquaSet]
}
it can "be constructed with apply" in {
val result1 = lower.SortedEquaMap("one" -> 1, "two" -> 2, "three" -> 3)
result1 should have size 3
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.TreeEquaMap("one" -> 1, "two" -> 2, "three" -> 3)
result2 should have size 3
result2.shouldHaveExactType[lower.TreeEquaMap[Int]]
// TODO: After moving enablers to scalactic, make a nominal typeclass
// instance for Size and Length for SortedEquaSet.
}
it should "construct only entries with appropriate key types" in {
"lower.SortedEquaMap(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")" shouldNot compile
"lower.TreeEquaMap(1 -> \"one\", 2 -> \"two\", 3 -> \"three\")" shouldNot compile
}
it should "eliminate 'duplicate' entries passed to the apply factory method" in {
val result1 = lower.SortedEquaMap("one" -> 1, "two" -> 22, "two" -> 2, "three" -> 33, "Three" -> 3)
result1 should have size 3
result1 shouldBe lower.SortedEquaMap("one" -> 1, "two" -> 2, "Three" -> 3)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.TreeEquaMap("one" -> 1, "two" -> 22, "two" -> 2, "three" -> 33, "Three" -> 3)
result2 should have size 3
result2 shouldBe lower.TreeEquaMap("one" -> 1, "two" -> 2, "Three" -> 3)
result2.shouldHaveExactType[lower.TreeEquaMap[Int]]
// TODO: After moving enablers to scalactic, make a nominal typeclass
// instance for Size and Length for SortedEquaSet.
}
it should "have a toString method" in {
lower.SortedEquaMap("hi" -> 1, "ho" -> 2).toString shouldBe "TreeEquaMap(hi -> 1, ho -> 2)"
lower.TreeEquaMap("hi" -> 1, "ho" -> 2).toString shouldBe "TreeEquaMap(hi -> 1, ho -> 2)"
}
it should "have a toMap method" in {
lower.SortedEquaMap("hi" -> 1, "ho" -> 2).toMap shouldBe (Map("hi" -> 1, "ho" -> 2))
}
it should "have a toEquaBoxMap method" in {
lower.SortedEquaMap("hi" -> 1, "ho" -> 2).toEquaBoxMap shouldBe (Map(lower.EquaBox("hi") -> 1, lower.EquaBox("ho") -> 2))
}
it should "have a + method that takes one argument" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3)
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3)
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3)
result3 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3)
result3.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result4 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3)
result4 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3)
result4.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a + method that takes two or more arguments" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) + ("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result4 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) + ("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a - method that takes one argument" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - "ha"
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) - "HO"
result2 shouldBe lower.SortedEquaMap("hi" -> 1)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) - "who?"
result3 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result4 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - "ha"
result4 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result4.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result5 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) - "HO"
result5 shouldBe lower.TreeEquaMap("hi" -> 1)
result5.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result6 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) - "who?"
result6 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result6.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a - method that takes two or more arguments" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - ("ha", "howdy!")
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) - ("HO", "FIE", "fUm")
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) - ("who", "goes", "thar")
result3 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result4 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) - ("HI", "HO")
result4 shouldBe lower.SortedEquaMap.empty
result4.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result5 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) - ("ha", "howdy!")
result5 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result6 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) - ("HO", "FIE", "fUm")
result6 shouldBe lower.TreeEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result7 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) - ("who", "goes", "thar")
result7 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result8 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) - ("HI", "HO")
result8 shouldBe lower.TreeEquaMap.empty[Int]
result8.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a keysIterator method that returns keys in sorted order" in {
lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "he" -> 4).keysIterator.toList shouldEqual List("ha", "he", "hi", "ho")
}
it should "have a valuesIterator method that returns keys in sorted order" in {
lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "he" -> 4).valuesIterator.toList shouldEqual List(3, 4, 1, 2) // sorted by the order of key
}
it should "have a ++ method that takes a GenTraversableOnce" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ List("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ List("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ Set("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result4 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ Set("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result5 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("ha" -> 3, "hey!" -> 4)
result5 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result5.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result6 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result6 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result6.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result7 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ List("ha" -> 3, "hey!" -> 4)
result7 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result7.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result8 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ List("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result8 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result8.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result9 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ Set("ha" -> 3, "hey!" -> 4)
result9 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result9.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result10 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ Set("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result10 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result10.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result11 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("ha" -> 3, "hey!" -> 4)
result11 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result11.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result12 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ Vector("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result12 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result12.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a ++ method that takes another EquaSet" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ lower.SortedEquaMap("ha" -> 3, "hey!" -> 4)
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) ++ lower.SortedEquaMap("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 3, "hoe" -> 4, "Ho!" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ lower.TreeEquaMap("ha" -> 3, "hey!" -> 4)
result3 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3, "hey!" -> 4)
result3.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result4 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) ++ lower.TreeEquaMap("HO" -> 3, "hoe" -> 4, "Ho!" -> 5)
result4 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 3, "Ho!" -> 5, "hoe" -> 4)
result4.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a -- method that takes a GenTraversableOnce" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- List("ha", "howdy!")
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- List("HO", "FIE", "fUm")
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- List("who", "goes", "thar")
result3 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result4 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- List("HI", "HO")
result4 shouldBe lower.SortedEquaMap.empty[Int]
result4.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result5 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Set("ha", "howdy!")
result5 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result6 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Set("HO", "FIE", "fUm")
result6 shouldBe lower.SortedEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result7 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- Set("who", "goes", "thar")
result7 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result8 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- Set("HI", "HO")
result8 shouldBe lower.SortedEquaMap.empty[Int]
result8.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result9 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Vector("ha", "howdy!")
result9 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result9.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result10 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Vector("HO", "FIE", "fUm")
result10 shouldBe lower.SortedEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result10.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result11 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- Vector("who", "goes", "thar")
result11 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result11.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result12 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- Vector("HI", "HO")
result12 shouldBe lower.SortedEquaMap.empty[Int]
result12.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result13 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- List("ha", "howdy!")
result13 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result13.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result14 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- List("HO", "FIE", "fUm")
result14 shouldBe lower.TreeEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result14.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result15 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- List("who", "goes", "thar")
result15 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result15.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result16 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- List("HI", "HO")
result16 shouldBe lower.TreeEquaMap.empty[Int]
result16.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result17 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Set("ha", "howdy!")
result17 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result17.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result18 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Set("HO", "FIE", "fUm")
result18 shouldBe lower.TreeEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result18.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result19 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- Set("who", "goes", "thar")
result19 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result19.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result20 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- Set("HI", "HO")
result20 shouldBe lower.TreeEquaMap.empty[Int]
result20.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result21 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- Vector("ha", "howdy!")
result21 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result21.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result22 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- Vector("HO", "FIE", "fUm")
result22 shouldBe lower.TreeEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result22.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result23 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- Vector("who", "goes", "thar")
result23 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result23.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result24 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- Vector("HI", "HO")
result24 shouldBe lower.TreeEquaMap.empty[Int]
result24.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a -- method that takes EquaSet" in {
val result1 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- lower.EquaSet("ha", "howdy!")
result1 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result1.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result2 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 5) -- lower.EquaSet("HO", "FIE", "fUm")
result2 shouldBe lower.SortedEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result2.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result3 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("who", "goes", "thar")
result3 shouldBe lower.SortedEquaMap("hi" -> 1, "ho" -> 2)
result3.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result4 = lower.SortedEquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("HI", "HO")
result4 shouldBe lower.SortedEquaMap.empty[Int]
result4.shouldHaveExactType[lower.SortedEquaMap[Int]]
val result5 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "ha" -> 3) -- lower.EquaSet("ha", "howdy!")
result5 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result5.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result6 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2, "fee" -> 3, "fie" -> 4, "foe" -> 5, "fum" -> 6) -- lower.EquaSet("HO", "FIE", "fUm")
result6 shouldBe lower.TreeEquaMap("hi" -> 1, "fee" -> 3, "foe" -> 5)
result6.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result7 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("who", "goes", "thar")
result7 shouldBe lower.TreeEquaMap("hi" -> 1, "ho" -> 2)
result7.shouldHaveExactType[lower.TreeEquaMap[Int]]
val result8 = lower.TreeEquaMap("hi" -> 1, "ho" -> 2) -- lower.EquaSet("HI", "HO")
result8 shouldBe lower.TreeEquaMap.empty[Int]
result8.shouldHaveExactType[lower.TreeEquaMap[Int]]
}
it should "have a /: method" in {
(0 /: lower.SortedEquaMap("one" -> 1))(_ + _._2) shouldBe 1
(1 /: lower.SortedEquaMap("one" -> 1))(_ + _._2) shouldBe 2
(0 /: lower.SortedEquaMap("one" -> 1, "two" -> 2, "three" -> 3))(_ + _._2) shouldBe 6
(1 /: lower.SortedEquaMap("one" -> 1, "two" -> 2, "three" -> 3))(_ + _._2) shouldBe 7
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/DiagrammedAssertionsSpec.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 SharedHelpers.thisLineNumber
import java.util.Date
import org.scalactic.Prettifier
import org.scalatest.exceptions.TestCanceledException
import org.scalatest.exceptions.TestFailedException
class DiagrammedAssertionsSpec extends FunSpec with Matchers with DiagrammedAssertions {
val fileName: String = "DiagrammedAssertionsSpec.scala"
class Stateful {
var state = false
def changeState: Boolean = {
state = true
state
}
}
class CustomInt(value: Int) {
def startsWith(v: Int): Boolean = {
value.toString.startsWith(v.toString)
}
def endsWith(v: Int): Boolean = {
value.toString.endsWith(v.toString)
}
def contains(v: Int): Boolean = {
value.toString.contains(v.toString)
}
def exists(v: Int): Boolean = {
value == v
}
override def toString: String = value.toString
}
class CustomContainer[+E](e: E) {
val element: E = e
def contains[E1 >: E](elem: E1): Boolean = elem == element
}
private def neverRuns1(f: => Unit): Boolean = true
private def neverRuns2(f: => Unit)(a: Int): Boolean = true
private def neverRuns3[T](f: => Unit)(a: T): Boolean = true
val s1 = "hi ScalaTest"
val s2 = "ScalaTest hi"
val s3 = "Say hi to ScalaTest"
val s4 = ""
val ci1 = new CustomInt(123)
val ci1Str = Prettifier.default(ci1)
val ci2 = new CustomInt(321)
val ci2Str = Prettifier.default(ci2)
val ci3 = ci1
val ci3Str = Prettifier.default(ci3)
val l1 = List(1, 2, 3)
val l2 = List.empty[Int]
val l3 = List("one", "two", "three")
val l3Str = Prettifier.default(l3)
val m1 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val m1Str = Prettifier.default(m1)
val m2 = Map.empty[Int, String]
val ct1 = new CustomContainer(8)
val ct1Str = Prettifier.default(ct1)
val date = new Date
def woof(f: => Unit) = "woof"
def meow(x: Int = 0, y: Int = 3) = "meow"
describe("DiagrammedAssertions") {
val a = 3
val b = 5
val c = "8"
val bob = "bob"
val alice = "alice"
describe("The assert(boolean) method") {
it("should do nothing when is used to check a == 3") {
assert(a == 3)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 5") {
val e = intercept[TestFailedException] {
assert(a == 5)
}
e.message should be (
Some(
"""
|
|assert(a == 5)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 == b") {
assert(5 == b)
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 == b") {
val e = intercept[TestFailedException] {
assert(3 == b)
}
e.message should be (
Some(
"""
|
|assert(3 == b)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a != 5") {
assert(a != 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a != 3") {
val e = intercept[TestFailedException] {
assert(a != 3)
}
e.message should be (
Some(
"""
|
|assert(a != 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 != b") {
assert(3 != b)
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 != b") {
val e = intercept[TestFailedException] {
assert(5 != b)
}
e.message should be (
Some(
"""
|
|assert(5 != b)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 == 3") {
assert(3 == 3)
}
it("should throw TestFailedException with message that contains the original code and correct stack depth when is used to check 3 == 5") {
// This is because the compiler simply pass the false boolean literal
// to the macro, can't find a way to get the 3 == 5 literal.
val e1 = intercept[TestFailedException] {
assert(3 == 5)
}
e1.message should be (
Some(
"""
|
|assert(3 == 5)
| |
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == b") {
val e = intercept[TestFailedException] {
assert(a == b)
}
e.message should be (
Some(
"""
|
|assert(a == b)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check c == null") {
val e = intercept[TestFailedException] {
assert(c == null)
}
e.message should be (
Some(
"""
|
|assert(c == null)
| | | |
| | | null
| | false
| "8"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check null == c") {
val e = intercept[TestFailedException] {
assert(null == c)
}
e.message should be (
Some(
"""
|
|assert(null == c)
| | | |
| null | "8"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 != a") {
val e = intercept[TestFailedException] {
assert(3 != a)
}
e.message should be (
Some(
"""
|
|assert(3 != a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 != a") {
assert(5 != a)
}
it("should do nothing when is used to check a > 2") {
assert(a > 2)
}
it("should do nothing when is used to check 5 > a") {
assert(5 > a)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a > 3") {
val e = intercept[TestFailedException] {
assert(a > 3)
}
e.message should be (
Some(
"""
|
|assert(a > 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 > a") {
val e = intercept[TestFailedException] {
assert(3 > a)
}
e.message should be (
Some(
"""
|
|assert(3 > a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a >= 3") {
assert(a >= 3)
}
it("should do nothing when is used to check 3 >= a") {
assert(3 >= a)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a >= 4") {
val e = intercept[TestFailedException] {
assert(a >= 4)
}
e.message should be (
Some(
"""
|
|assert(a >= 4)
| | | |
| 3 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 2 >= a") {
val e = intercept[TestFailedException] {
assert(2 >= a)
}
e.message should be (
Some(
"""
|
|assert(2 >= a)
| | | |
| 2 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b < 6") {
assert(b < 6)
}
it("should do nothing when is used to check 3 < b") {
assert(3 < b)
}
it("should throw TestFailedException with correct message and stack depth when is used to check b < 5") {
val e = intercept[TestFailedException] {
assert(b < 5)
}
e.message should be (
Some(
"""
|
|assert(b < 5)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 < b") {
val e = intercept[TestFailedException] {
assert(5 < b)
}
e.message should be (
Some(
"""
|
|assert(5 < b)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b <= 5") {
assert(b <= 5)
}
it("should do nothing when is used to check 5 <= b") {
assert(5 <= b)
}
it("should throw TestFailedException with correct message and stack depth when is used to check b <= 4") {
val e = intercept[TestFailedException] {
assert(b <= 4)
}
e.message should be (
Some(
"""
|
|assert(b <= 4)
| | | |
| 5 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 6 <= b") {
val e = intercept[TestFailedException] {
assert(6 <= b)
}
e.message should be (
Some(
"""
|
|assert(6 <= b)
| | | |
| 6 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check bob == \"bob\"") {
assert(bob == "bob")
}
it("should do nothing when is used to check bob != \"alice\"") {
assert(bob != "alice")
}
it("should do nothing when is used to check alice == \"alice\"") {
assert(alice == "alice")
}
it("should do nothing when is used to check alice != \"bob\"") {
assert(alice != "bob")
}
it("should throw TestFailedException with correct message and stack depth when is used to check bob == \"alice\"") {
val e = intercept[TestFailedException] {
assert(bob == "alice")
}
e.message should be (
Some(
"""
|
|assert(bob == "alice")
| | | |
| | | "alice"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check bob != \"bob\"") {
val e = intercept[TestFailedException] {
assert(bob != "bob")
}
e.message should be (
Some(
"""
|
|assert(bob != "bob")
| | | |
| | | "bob"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check alice == \"bob\"") {
val e = intercept[TestFailedException] {
assert(alice == "bob")
}
e.message should be (
Some(
"""
|
|assert(alice == "bob")
| | | |
| | | "bob"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check alice != \"alice\"") {
val e = intercept[TestFailedException] {
assert(alice != "alice")
}
e.message should be (
Some(
"""
|
|assert(alice != "alice")
| | | |
| | | "alice"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check a === 3") {
assert(a === 3)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a === 5 ") {
val e = intercept[TestFailedException] {
assert(a === 5)
}
e.message should be (
Some(
"""
|
|assert(a === 5)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 === a") {
assert(3 === a)
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 === a") {
val e = intercept[TestFailedException] {
assert(5 === a)
}
e.message should be (
Some(
"""
|
|assert(5 === a)
| | | |
| 5 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a !== 5") {
assert(a !== 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a !== 3") {
val e = intercept[TestFailedException] {
assert(a !== 3)
}
e.message should be (
Some(
"""
|
|assert(a !== 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 !== a") {
assert(5 !== a)
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 !== a") {
val e = intercept[TestFailedException] {
assert(3 !== a)
}
e.message should be (
Some(
"""
|
|assert(3 !== a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 && b == 5") {
assert(a == 3 && b == 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && b == 6") {
val e = intercept[TestFailedException] {
assert(a == 3 && b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 3 && b == 6)
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 && b == 5") {
val e = intercept[TestFailedException] {
assert(a == 2 && b == 5)
}
e.message should be (
Some(
"""
|
|assert(a == 2 && b == 5)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 && b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 && b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 2 && b == 6)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 & b == 5") {
assert(a == 3 & b == 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 & b == 6") {
val e = intercept[TestFailedException] {
assert(a == 3 & b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 3 & b == 6)
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 & b == 5") {
val e = intercept[TestFailedException] {
assert(a == 2 & b == 5)
}
e.message should be (
Some(
"""
|
|assert(a == 2 & b == 5)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 & b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 & b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 2 & b == 6)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 || b == 5") {
assert(a == 3 || b == 5)
}
it("should do nothing when is used to check a == 3 || b == 6") {
assert(a == 3 || b == 6)
}
it("should do nothing when is used to check a == 2 || b == 5") {
assert(a == 2 || b == 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 || b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 || b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 2 || b == 6)
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 | b == 5") {
assert(a == 3 | b == 5)
}
it("should do nothing when is used to check a == 3 | b == 6") {
assert(a == 3 | b == 6)
}
it("should do nothing when is used to check a == 2 | b == 5") {
assert(a == 2 | b == 5)
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 | b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 | b == 6)
}
e.message should be (
Some(
"""
|
|assert(a == 2 | b == 6)
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 && (b == 5 && b > 3)") {
assert(a == 3 && (b == 5 && b > 3))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && (b == 5 && b > 5)") {
val e = intercept[TestFailedException] {
assert(a == 3 && (b == 5 && b > 5))
}
e.message should be (
Some(
"""
|
|assert(a == 3 && (b == 5 && b > 5))
| | | | | | | | | | | |
| 3 | 3 | 5 | 5 | 5 | 5
| true false true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(a == 5)") {
assert(!(a == 5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(a == 3)") {
val e = intercept[TestFailedException] {
assert(!(a == 3))
}
e.message should be (
Some(
"""
|
|assert(!(a == 3))
| | | | |
| | 3 | 3
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && !(b == 5)") {
val e = intercept[TestFailedException] {
assert(a == 3 && !(b == 5))
}
e.message should be (
Some(
"""
|
|assert(a == 3 && !(b == 5))
| | | | | | | | |
| 3 | 3 | | 5 | 5
| true | | true
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check (a == 3) == (b == 5)") {
assert((a == 3) == (b == 5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check (a == 3) == (b != 5)") {
val e = intercept[TestFailedException] {
assert((a == 3) == (b != 5))
}
e.message should be (
Some(
"""
|
|assert((a == 3) == (b != 5))
| | | | | | | |
| 3 | 3 | 5 | 5
| true false false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should short-circuit && when first condition was false") {
val s = new Stateful
intercept[TestFailedException] {
assert(a == 5 && s.changeState)
}
s.state should be (false)
}
it("should short-circuit & when first condition was false") {
val s = new Stateful
intercept[TestFailedException] {
assert(a == 5 & s.changeState)
}
s.state should be (false)
}
it("should short-circuit || when first condition was true") {
val s = new Stateful
assert(a == 3 || s.changeState)
s.state should be (false)
}
it("should short-circuit | when first condition was true") {
val s = new Stateful
assert(a == 3 | s.changeState)
s.state should be (false)
}
it("should do nothing when it is used to check a == 3 && { println(\"hi\"); b == 5} ") {
assert(a == 3 && { println("hi"); b == 5})
}
it("should throw TestFailedException with correct message and stack depth when is usesd to check a == 3 && { println(\"hi\"); b == 3}") {
val e = intercept[TestFailedException] {
assert(a == 3 && { println("hi"); b == 3})
}
e.message should be (
Some(
"""
|
|assert(a == 3 && { println("hi"); b == 3})
| | | | | | | |
| 3 | 3 false 5 | 3
| true false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when it is used to check { println(\"hi\"); b == 5} && a == 3") {
assert({ println("hi"); b == 5} && a == 3)
}
it("should throw TestFailedException with correct message and stack depth when is usesd to check { println(\"hi\"); b == 5} && a == 5") {
val e = intercept[TestFailedException] {
assert({ println("hi"); b == 5} && a == 5)
}
e.message should be (
Some(
"""
|
|assert({ println("hi"); b == 5} && a == 5)
| | | | | | | |
| 5 | 5 | 3 | 5
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should preserve side effects when Apply with single argument is passed in") {
assert(neverRuns1(sys.error("Sad times 1")))
}
it("should preserve side effects when Apply with 2 argument list is passed in") {
assert(neverRuns2(sys.error("Sad times 2"))(0))
}
it("should preserve side effects when typed Apply with 2 argument list is passed in") {
assert(neverRuns3(sys.error("Sad times 3"))(0))
}
it("should do nothing when is used to check s1 startsWith \"hi\"") {
assert(s1 startsWith "hi")
assert(s1.startsWith("hi"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check s2 startsWith \"hi\"") {
val e1 = intercept[TestFailedException] {
assert(s2 startsWith "hi")
}
e1.message should be (
Some(
"""
|
|assert(s2 startsWith "hi")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s2.startsWith("hi"))
}
e2.message should be (
Some(
"""
|
|assert(s2.startsWith("hi"))
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci1 startsWith 1") {
assert(ci1 startsWith 1)
assert(ci1.startsWith(1))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci2 startsWith 1") {
val e1 = intercept[TestFailedException] {
assert(ci2 startsWith 1)
}
e1.message should be (
Some(
"""
|
|assert(ci2 startsWith 1)
| | | |
| 321 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci2.startsWith(1))
}
e2.message should be (
Some(
"""
|
|assert(ci2.startsWith(1))
| | | |
| 321 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s2.startsWith(\"hi\")") {
assert(!s2.startsWith("hi"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s1.startsWith(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s1.startsWith("hi"))
}
e1.message should be (
Some(
"""
|
|assert(!s1.startsWith("hi"))
| || | |
| || true "hi"
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s2 endsWith \"hi\"") {
assert(s2 endsWith "hi")
assert(s2.endsWith("hi"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1 endsWith \"hi\"") {
val e1 = intercept[TestFailedException] {
assert(s1 endsWith "hi")
}
e1.message should be (
Some(
"""
|
|assert(s1 endsWith "hi")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s1.endsWith("hi"))
}
e2.message should be (
Some(
"""
|
|assert(s1.endsWith("hi"))
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 endsWith 1") {
assert(ci2 endsWith 1)
assert(ci2.endsWith(1))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 endsWith 1") {
val e1 = intercept[TestFailedException] {
assert(ci1 endsWith 1)
}
e1.message should be (
Some(
"""
|
|assert(ci1 endsWith 1)
| | | |
| 123 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci1.endsWith(1))
}
e2.message should be (
Some(
"""
|
|assert(ci1.endsWith(1))
| | | |
| 123 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.endsWith(\"hi\")") {
assert(!s1.endsWith("hi"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s2.endsWith(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s2.endsWith("hi"))
}
e1.message should be (
Some(
"""
|
|assert(!s2.endsWith("hi"))
| || | |
| || true "hi"
| |"ScalaTest hi"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s3 contains \"hi\"") {
assert(s3 contains "hi")
assert(s3.contains("hi"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check s3 contains \"hello\"") {
val e1 = intercept[TestFailedException] {
assert(s3 contains "hello")
}
e1.message should be (
Some(
"""
|
|assert(s3 contains "hello")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s3.contains("hello"))
}
e2.message should be (
Some(
"""
|
|assert(s3.contains("hello"))
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 contains 2") {
assert(ci2 contains 2)
assert(ci2.contains(2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(ci1 contains 5)
}
e1.message should be (
Some(
"""
|
|assert(ci1 contains 5)
| | | |
| 123 false 5
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci1.contains(5))
}
e2.message should be (
Some(
"""
|
|assert(ci1.contains(5))
| | | |
| 123 false 5
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.contains(\"hello\")") {
assert(!s3.contains("hello"))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s3.contains(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s3.contains("hi"))
}
e1.message should be (
Some(
"""
|
|assert(!s3.contains("hi"))
| || | |
| || true "hi"
| |"Say hi to ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1 contains 2") {
assert(l1 contains 2)
assert(l1.contains(2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(l1 contains 5)
}
e1.message should be (
Some(
"""
|
|assert(l1 contains 5)
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(l1.contains(5))
}
e2.message should be (
Some(
"""
|
|assert(l1.contains(5))
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(l1 contains 5)") {
assert(!(l1 contains 5))
assert(!l1.contains(5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1 contains 2)") {
val e1 = intercept[TestFailedException] {
assert(!(l1 contains 2))
}
e1.message should be (
Some(
"""
|
|assert(!(l1 contains 2))
| | | | |
| | | true 2
| | List(1, 2, 3)
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestFailedException] {
assert(!l1.contains(2))
}
e2.message should be (
Some(
"""
|
|assert(!l1.contains(2))
| || | |
| || true 2
| |List(1, 2, 3)
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check m1 contains 2") {
assert(m1 contains 2)
assert(m1.contains(2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check m1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(m1 contains 5)
}
e1.message should be (
Some(
s"""
|
|assert(m1 contains 5)
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(m1.contains(5))
}
e2.message should be (
Some(
s"""
|
|assert(m1.contains(5))
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(m1 contains 5)") {
assert(!(m1 contains 5))
assert(!m1.contains(5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(m1 contains 2)") {
val e1 = intercept[TestFailedException] {
assert(!(m1 contains 2))
}
e1.message should be (
Some(
s"""
|
|assert(!(m1 contains 2))
| | | | |
| | | true 2
| | $m1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestFailedException] {
assert(!m1.contains(2))
}
e2.message should be (
Some(
s"""
|
|assert(!m1.contains(2))
| || | |
| || true 2
| |$m1Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ct1 contains 8") {
assert(ct1 contains 8)
assert(ct1.contains(8))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ct1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(ct1 contains 5)
}
e1.message should be (
Some(
s"""
|
|assert(ct1 contains 5)
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ct1.contains(5))
}
e2.message should be (
Some(
s"""
|
|assert(ct1.contains(5))
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ct1.contains(5)") {
assert(!ct1.contains(5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ct1.contains(8)") {
val e1 = intercept[TestFailedException] {
assert(!ct1.contains(8))
}
e1.message should be (
Some(
s"""
|
|assert(!ct1.contains(8))
| || | |
| || true 8
| |$ct1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 eq ci3") {
assert(ci1 eq ci3)
assert(ci1.eq(ci3))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 eq ci2") {
val e1 = intercept[TestFailedException] {
assert(ci1 eq ci2)
}
e1.message should be (
Some(
s"""
|
|assert(ci1 eq ci2)
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ci1.eq(ci2))
}
e2.message should be (
Some(
s"""
|
|assert(ci1.eq(ci2))
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.eq(ci2)") {
assert(!ci1.eq(ci2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ci1.eq(ci3)") {
val e = intercept[TestFailedException] {
assert(!ci1.eq(ci3))
}
e.message should be (
Some(
s"""
|
|assert(!ci1.eq(ci3))
| || | |
| |$ci1Str | $ci3Str
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 ne ci2") {
assert(ci1 ne ci2)
assert(ci1.ne(ci2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 ne ci3") {
val e1 = intercept[TestFailedException] {
assert(ci1 ne ci3)
}
e1.message should be (
Some(
s"""
|
|assert(ci1 ne ci3)
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ci1.ne(ci3))
}
e2.message should be (
Some(
s"""
|
|assert(ci1.ne(ci3))
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.ne(ci3)") {
assert(!ci1.ne(ci3))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ci1.ne(ci2)") {
val e = intercept[TestFailedException] {
assert(!ci1.ne(ci2))
}
e.message should be (
Some(
"""
|
|assert(!ci1.ne(ci2))
| || | |
| |123 | 321
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s4.isEmpty") {
assert(s4.isEmpty)
}
it("should throw TestFailedException with correct message and stack depth when is used to check s3.isEmpty") {
val e = intercept[TestFailedException] {
assert(s3.isEmpty)
}
e.message should be (
Some(
"""
|
|assert(s3.isEmpty)
| | |
| | false
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !s3.isEmpty") {
assert(!s3.isEmpty)
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s4.isEmpty") {
val e = intercept[TestFailedException] {
assert(!s4.isEmpty)
}
e.message should be (
Some(
"""
|
|assert(!s4.isEmpty)
| || |
| |"" true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l2.isEmpty") {
assert(l2.isEmpty)
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isEmpty") {
val e = intercept[TestFailedException] {
assert(l1.isEmpty)
}
e.message should be (
Some(
s"""
|
|assert(l1.isEmpty)
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isEmpty") {
assert(!l1.isEmpty)
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l2.isEmpty") {
val e = intercept[TestFailedException] {
assert(!l2.isEmpty)
}
e.message should be (
Some(
s"""
|
|assert(!l2.isEmpty)
| || |
| || true
| |$l2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.isInstanceOf[String]") {
assert(s1.isInstanceOf[String])
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isInstanceOf[String]") {
val e = intercept[TestFailedException] {
assert(l1.isInstanceOf[String])
}
e.message should be (
Some(
s"""
|
|assert(l1.isInstanceOf[String])
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l1.isInstanceOf[List[Int]]") {
assert(l1.isInstanceOf[List[Int]])
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.isInstanceOf[List[Int]]") {
val e = intercept[TestFailedException] {
assert(s1.isInstanceOf[List[Int]])
}
e.message should be (
Some(
"""
|
|assert(s1.isInstanceOf[List[Int]])
| | |
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check date.isInstanceOf[Date]") {
assert(date.isInstanceOf[Date])
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isInstanceOf[Date]") {
val e = intercept[TestFailedException] {
assert(l1.isInstanceOf[Date])
}
e.message should be (
Some(
s"""
|
|assert(l1.isInstanceOf[Date])
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isInstanceOf[String]") {
assert(!l1.isInstanceOf[String])
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s1.isInstanceOf[String]") {
val e = intercept[TestFailedException] {
assert(!s1.isInstanceOf[String])
}
e.message should be (
Some(
"""
|
|assert(!s1.isInstanceOf[String])
| || |
| || true
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !s1.isInstanceOf[List[Int]]") {
assert(!s1.isInstanceOf[List[Int]])
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l1.isInstanceOf[List[Int]]") {
val e = intercept[TestFailedException] {
assert(!l1.isInstanceOf[List[Int]])
}
e.message should be (
Some(
s"""
|
|assert(!l1.isInstanceOf[List[Int]])
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !l1.isInstanceOf[Date]") {
assert(!l1.isInstanceOf[Date])
}
it("should throw TestFailedException with correct message and stack depth when is used to check !date.isInstanceOf[Date]") {
val e = intercept[TestFailedException] {
assert(!date.isInstanceOf[Date])
}
e.message should be (
Some(
s"""
|
|assert(!date.isInstanceOf[Date])
| || |
| || true
| |$date
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.length == 9") {
assert(s1.length == 12)
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.length == 10") {
val e = intercept[TestFailedException] {
assert(s1.length == 10)
}
e.message should be (
Some(
"""
|
|assert(s1.length == 10)
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.length == 3") {
assert(l1.length == 3)
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.length == 10") {
val e = intercept[TestFailedException] {
assert(l1.length == 10)
}
e.message should be (
Some(
s"""
|
|assert(l1.length == 10)
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.length == 10)") {
assert(!(s1.length == 10))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(s1.length == 9)") {
val e = intercept[TestFailedException] {
assert(!(s1.length == 12))
}
e.message should be (
Some(
"""
|
|assert(!(s1.length == 12))
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.length == 2)") {
assert(!(l1.length == 2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1.length == 9)") {
val e = intercept[TestFailedException] {
assert(!(l1.length == 3))
}
e.message should be (
Some(
s"""
|
|assert(!(l1.length == 3))
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check s1.size == 9") {
assert(s1.size == 12)
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.size == 10") {
val e = intercept[TestFailedException] {
assert(s1.size == 10)
}
e.message should be (
Some(
"""
|
|assert(s1.size == 10)
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.size == 3") {
assert(l1.size == 3)
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.size == 10") {
val e = intercept[TestFailedException] {
assert(l1.size == 10)
}
e.message should be (
Some(
s"""
|
|assert(l1.size == 10)
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.size == 10)") {
assert(!(s1.size == 10))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(s1.size == 9)") {
val e = intercept[TestFailedException] {
assert(!(s1.size == 12))
}
e.message should be (
Some(
"""
|
|assert(!(s1.size == 12))
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.size == 2)") {
assert(!(l1.size == 2))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1.size == 9) ") {
val e = intercept[TestFailedException] {
assert(!(l1.size == 3))
}
e.message should be (
Some(
s"""
|
|assert(!(l1.size == 3))
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check l1.exists(_ == 3)") {
assert(l1.exists(_ == 3))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.exists(_ == 5) ") {
val e = intercept[TestFailedException] {
assert(l1.exists(_ == 5))
}
e.message should be (
Some(
s"""
|
|assert(l1.exists(_ == 5))
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.exists(_ == 5)") {
assert(!l1.exists(_ == 5))
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l1.exists(_ == 3)") {
val e = intercept[TestFailedException] {
assert(!l1.exists(_ == 3))
}
e.message should be (
Some(
s"""
|
|assert(!l1.exists(_ == 3))
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.exists(_ > 3)") {
val e = intercept[TestFailedException] {
assert(l1.exists(_ > 3))
}
e.message should be (
Some(
s"""
|
|assert(l1.exists(_ > 3))
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l3.exists(_.isEmpty)") {
val e = intercept[TestFailedException] {
assert(l3.exists(_.isEmpty))
}
e.message should be (
Some(
s"""
|
|assert(l3.exists(_.isEmpty))
| | |
| | false
| $l3Str
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l3.exists(false)") {
val e = intercept[TestFailedException] {
assert(ci1.exists(321))
}
e.message should be (
Some(
"""
|
|assert(ci1.exists(321))
| | | |
| 123 false 321
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when used to check woof { meow(y = 5) } == \"woof\" ") {
assert(woof { meow(y = 5) } == "woof")
}
it("should throw TestFailedException with correct message and stack depth when is used to check woof { meow(y = 5) } == \"meow\"") {
val e = intercept[TestFailedException] {
assert(woof { meow(y = 5) } == "meow")
}
e.message should be (
Some(
"""
|
|assert(woof { meow(y = 5) } == "meow")
| | | |
| "woof" | "meow"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when used to check multiline assert((b == a + 2) && (b - 2 <= a)) ") {
assert((b == a + 2) && (b - 2 <=
a))
}
it("should throw friend message when used to check multiline assert((b == a + 2) && (b - 1 <= a))") {
val e = intercept[TestFailedException] {
assert((b == a + 2) && (b - 1 <=
a))
}
e.message shouldBe Some("5 equaled 5, but 4 was not less than or equal to 3")
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
}
it("should do nothing when a block of code that evaluates to true is passed in") {
assert {
val a = 1
val b = 2
val c = a + b
a < b || c == a + b
}
}
it("should throw TestFailedException with correct message and stack depth when a block of code that evaluates to false is passed") {
val e = intercept[TestFailedException] {
assert { val a = 1; val b = 2; val c = a + b; a > b || c == b * b }
}
e.message should be (
Some(
"""
|
|assert { val a = 1; val b = 2; val c = a + b; a > b || c == b * b }
| | | | | | | | | |
| 1 | 2 | 3 | 2 4 2
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should fallback to BooleanMacro when a block of code > 1 line is passed in ") {
val e = intercept[TestFailedException] {
assert {
val a = 1
val b = 2
val c = a + b
a > b || c == b * b }
}
e.message should be (
Some(
"""{
| val a: Int = 1;
| val b: Int = 2;
| val c: Int = a.+(b);
| a.>(b).||(c.==(b.*(b)))
|} was false""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 17))
}
it("should do nothing when used to check <person>Dude</person> == <person>Dude</person>") {
assert(<person>Dude</person> == <person>Dude</person>)
}
it("should throw TestFailedException with correct message and stack depth when is used to check <person>Dude</person> == <person>Mary</person>") {
val e = intercept[TestFailedException] {
assert(<person>Dude</person> == <person>Mary</person>)
}
e.message should be (
Some(
"""
|
|assert(<person>Dude</person> == <person>Mary</person>)
| | | |
| | | <person>Mary</person>
| | false
| <person>Dude</person>
|""".stripMargin
)
)
}
it("should compile when used with org == xxx that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "test"
|assert(org == "test")
""".stripMargin)
}
it("should compile when used with org === xxx that shadow org.scalactic") {
assertCompiles(
"""
|val org = "test"
|assert(org === "test")
""".stripMargin)
}
it("should compile when used with org === xxx with TypeCheckedTripleEquals that shadow org.scalactic") {
assertCompiles(
"""
|class TestSpec extends FunSpec with org.scalactic.TypeCheckedTripleEquals {
| it("testing here") {
| val org = "test"
| assert(org === "test")
| }
|}
""".stripMargin)
}
it("should compile when used with org.aCustomMethod that shadow org.scalactic") {
assertCompiles(
"""
|class Test {
| def aCustomMethod: Boolean = true
|}
|val org = new Test
|assert(org.aCustomMethod)
""".stripMargin)
}
it("should compile when used with !org that shadow org.scalactic") {
assertCompiles(
"""
|val org = false
|assert(!org)
""".stripMargin)
}
it("should compile when used with org.isEmpty that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.isEmpty)
""".stripMargin)
}
it("should compile when used with org.isInstanceOf that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.isInstanceOf[String])
""".stripMargin)
}
it("should compile when used with org.size == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = Array.empty[String]
|assert(org.size == 0)
""".stripMargin)
}
it("should compile when used with org.length == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.length == 0)
""".stripMargin)
}
it("should compile when used with org.exists(_ == 'b') that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "abc"
|assert(org.exists(_ == 'b'))
""".stripMargin)
}
it("should do nothing when is used to check new String(\"test\") != \"test\"") {
assert(new String("test") == "test")
}
it("should throw TestFailedException with correct message and stack depth when is used to check new String(\"test\") != \"testing\"") {
val e = intercept[TestFailedException] {
assert(new String("test") == "testing")
}
e.message should be (
Some(
"""
|
|assert(new String("test") == "testing")
| | | |
| "test" | "testing"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
}
describe("The assert(boolean, clue) method") {
it("should do nothing when is used to check a == 3") {
assert(a == 3, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 5") {
val e = intercept[TestFailedException] {
assert(a == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 5, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 == b") {
assert(5 == b, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 == b") {
val e = intercept[TestFailedException] {
assert(3 == b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(3 == b, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a != 5") {
assert(a != 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a != 3") {
val e = intercept[TestFailedException] {
assert(a != 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a != 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 != b") {
assert(3 != b, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 != b") {
val e = intercept[TestFailedException] {
assert(5 != b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(5 != b, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 == 3") {
assert(3 == 3, "this is a clue")
}
it("should throw TestFailedException with message that contains the original code and correct stack depth when is used to check 3 == 5") {
// This is because the compiler simply pass the false boolean literal
// to the macro, can't find a way to get the 3 == 5 literal.
val e1 = intercept[TestFailedException] {
assert(3 == 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(3 == 5, "this is a clue")
| |
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == b") {
val e = intercept[TestFailedException] {
assert(a == b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == b, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check c == null") {
val e = intercept[TestFailedException] {
assert(c == null, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(c == null, "this is a clue")
| | | |
| | | null
| | false
| "8"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check null == c") {
val e = intercept[TestFailedException] {
assert(null == c, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(null == c, "this is a clue")
| | | |
| null | "8"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 != a") {
val e = intercept[TestFailedException] {
assert(3 != a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(3 != a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 != a") {
assert(5 != a, "this is a clue")
}
it("should do nothing when is used to check a > 2") {
assert(a > 2, "this is a clue")
}
it("should do nothing when is used to check 5 > a") {
assert(5 > a, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a > 3") {
val e = intercept[TestFailedException] {
assert(a > 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a > 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 > a") {
val e = intercept[TestFailedException] {
assert(3 > a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(3 > a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a >= 3") {
assert(a >= 3, "this is a clue")
}
it("should do nothing when is used to check 3 >= a") {
assert(3 >= a, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a >= 4") {
val e = intercept[TestFailedException] {
assert(a >= 4, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a >= 4, "this is a clue")
| | | |
| 3 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 2 >= a") {
val e = intercept[TestFailedException] {
assert(2 >= a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(2 >= a, "this is a clue")
| | | |
| 2 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b < 6") {
assert(b < 6, "this is a clue")
}
it("should do nothing when is used to check 3 < b") {
assert(3 < b, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check b < 5") {
val e = intercept[TestFailedException] {
assert(b < 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(b < 5, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 < b") {
val e = intercept[TestFailedException] {
assert(5 < b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(5 < b, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b <= 5") {
assert(b <= 5, "this is a clue")
}
it("should do nothing when is used to check 5 <= b") {
assert(5 <= b, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check b <= 4") {
val e = intercept[TestFailedException] {
assert(b <= 4, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(b <= 4, "this is a clue")
| | | |
| 5 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check 6 <= b") {
val e = intercept[TestFailedException] {
assert(6 <= b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(6 <= b, "this is a clue")
| | | |
| 6 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check bob == \"bob\"") {
assert(bob == "bob", "this is a clue")
}
it("should do nothing when is used to check bob != \"alice\"") {
assert(bob != "alice", "this is a clue")
}
it("should do nothing when is used to check alice == \"alice\"") {
assert(alice == "alice", "this is a clue")
}
it("should do nothing when is used to check alice != \"bob\"") {
assert(alice != "bob", "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check bob == \"alice\"") {
val e = intercept[TestFailedException] {
assert(bob == "alice", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(bob == "alice", "this is a clue")
| | | |
| | | "alice"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check bob != \"bob\"") {
val e = intercept[TestFailedException] {
assert(bob != "bob", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(bob != "bob", "this is a clue")
| | | |
| | | "bob"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check alice == \"bob\"") {
val e = intercept[TestFailedException] {
assert(alice == "bob", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(alice == "bob", "this is a clue")
| | | |
| | | "bob"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check alice != \"alice\"") {
val e = intercept[TestFailedException] {
assert(alice != "alice", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(alice != "alice", "this is a clue")
| | | |
| | | "alice"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check a === 3") {
assert(a === 3, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a === 5 ") {
val e = intercept[TestFailedException] {
assert(a === 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a === 5, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 === a") {
assert(3 === a, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check 5 === a") {
val e = intercept[TestFailedException] {
assert(5 === a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(5 === a, "this is a clue")
| | | |
| 5 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a !== 5") {
assert(a !== 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a !== 3") {
val e = intercept[TestFailedException] {
assert(a !== 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a !== 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 !== a") {
assert(5 !== a, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check 3 !== a") {
val e = intercept[TestFailedException] {
assert(3 !== a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(3 !== a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 && b == 5") {
assert(a == 3 && b == 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && b == 6") {
val e = intercept[TestFailedException] {
assert(a == 3 && b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 3 && b == 6, "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 && b == 5") {
val e = intercept[TestFailedException] {
assert(a == 2 && b == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 && b == 5, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 && b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 && b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 && b == 6, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 & b == 5") {
assert(a == 3 & b == 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 & b == 6") {
val e = intercept[TestFailedException] {
assert(a == 3 & b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 3 & b == 6, "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 & b == 5") {
val e = intercept[TestFailedException] {
assert(a == 2 & b == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 & b == 5, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 & b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 & b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 & b == 6, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 || b == 5") {
assert(a == 3 || b == 5, "this is a clue")
}
it("should do nothing when is used to check a == 3 || b == 6") {
assert(a == 3 || b == 6, "this is a clue")
}
it("should do nothing when is used to check a == 2 || b == 5") {
assert(a == 2 || b == 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 || b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 || b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 || b == 6, "this is a clue")
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 | b == 5") {
assert(a == 3 | b == 5, "this is a clue")
}
it("should do nothing when is used to check a == 3 | b == 6") {
assert(a == 3 | b == 6, "this is a clue")
}
it("should do nothing when is used to check a == 2 | b == 5") {
assert(a == 2 | b == 5, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 2 | b == 6") {
val e = intercept[TestFailedException] {
assert(a == 2 | b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 2 | b == 6, "this is a clue")
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 && (b == 5 && b > 3)") {
assert(a == 3 && (b == 5 && b > 3), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && (b == 5 && b > 5)") {
val e = intercept[TestFailedException] {
assert(a == 3 && (b == 5 && b > 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 3 && (b == 5 && b > 5), "this is a clue")
| | | | | | | | | | | |
| 3 | 3 | 5 | 5 | 5 | 5
| true false true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(a == 5)") {
assert(!(a == 5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(a == 3)") {
val e = intercept[TestFailedException] {
assert(!(a == 3), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!(a == 3), "this is a clue")
| | | | |
| | 3 | 3
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check a == 3 && !(b == 5)") {
val e = intercept[TestFailedException] {
assert(a == 3 && !(b == 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 3 && !(b == 5), "this is a clue")
| | | | | | | | |
| 3 | 3 | | 5 | 5
| true | | true
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check (a == 3) == (b == 5)") {
assert((a == 3) == (b == 5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check (a == 3) == (b != 5)") {
val e = intercept[TestFailedException] {
assert((a == 3) == (b != 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert((a == 3) == (b != 5), "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 5
| true false false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should short-circuit && when first condition was false") {
val s = new Stateful
intercept[TestFailedException] {
assert(a == 5 && s.changeState, "this is a clue")
}
s.state should be (false)
}
it("should short-circuit & when first condition was false") {
val s = new Stateful
intercept[TestFailedException] {
assert(a == 5 & s.changeState, "this is a clue")
}
s.state should be (false)
}
it("should short-circuit || when first condition was true") {
val s = new Stateful
assert(a == 3 || s.changeState, "this is a clue")
s.state should be (false)
}
it("should short-circuit | when first condition was true") {
val s = new Stateful
assert(a == 3 | s.changeState, "this is a clue")
s.state should be (false)
}
it("should do nothing when it is used to check a == 3 && { println(\"hi\"); b == 5} ") {
assert(a == 3 && { println("hi"); b == 5}, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is usesd to check a == 3 && { println(\"hi\"); b == 3}") {
val e = intercept[TestFailedException] {
assert(a == 3 && { println("hi"); b == 3}, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(a == 3 && { println("hi"); b == 3}, "this is a clue")
| | | | | | | |
| 3 | 3 false 5 | 3
| true false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when it is used to check { println(\"hi\"); b == 5} && a == 3") {
assert({ println("hi"); b == 5} && a == 3, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is usesd to check { println(\"hi\"); b == 5} && a == 5") {
val e = intercept[TestFailedException] {
assert({ println("hi"); b == 5} && a == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert({ println("hi"); b == 5} && a == 5, "this is a clue")
| | | | | | | |
| 5 | 5 | 3 | 5
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should preserve side effects when Apply with single argument is passed in") {
assert(neverRuns1(sys.error("Sad times 1")), "this is a clue")
}
it("should preserve side effects when Apply with 2 argument list is passed in") {
assert(neverRuns2(sys.error("Sad times 2"))(0), "this is a clue")
}
it("should preserve side effects when typed Apply with 2 argument list is passed in") {
assert(neverRuns3(sys.error("Sad times 3"))(0), "this is a clue")
}
it("should do nothing when is used to check s1 startsWith \"hi\"") {
assert(s1 startsWith "hi", "this is a clue")
assert(s1.startsWith("hi"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s2 startsWith \"hi\"") {
val e1 = intercept[TestFailedException] {
assert(s2 startsWith "hi", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(s2 startsWith "hi", "this is a clue")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s2.startsWith("hi"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(s2.startsWith("hi"), "this is a clue")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci1 startsWith 1") {
assert(ci1 startsWith 1, "this is a clue")
assert(ci1.startsWith(1), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci2 startsWith 1") {
val e1 = intercept[TestFailedException] {
assert(ci2 startsWith 1, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(ci2 startsWith 1, "this is a clue")
| | | |
| 321 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci2.startsWith(1), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(ci2.startsWith(1), "this is a clue")
| | | |
| 321 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s2.startsWith(\"hi\")") {
assert(!s2.startsWith("hi"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s1.startsWith(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s1.startsWith("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(!s1.startsWith("hi"), "this is a clue")
| || | |
| || true "hi"
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s2 endsWith \"hi\"") {
assert(s2 endsWith "hi", "this is a clue")
assert(s2.endsWith("hi"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1 endsWith \"hi\"") {
val e1 = intercept[TestFailedException] {
assert(s1 endsWith "hi", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(s1 endsWith "hi", "this is a clue")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s1.endsWith("hi"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(s1.endsWith("hi"), "this is a clue")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 endsWith 1") {
assert(ci2 endsWith 1, "this is a clue")
assert(ci2.endsWith(1), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 endsWith 1") {
val e1 = intercept[TestFailedException] {
assert(ci1 endsWith 1, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(ci1 endsWith 1, "this is a clue")
| | | |
| 123 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci1.endsWith(1), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(ci1.endsWith(1), "this is a clue")
| | | |
| 123 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.endsWith(\"hi\")") {
assert(!s1.endsWith("hi"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s2.endsWith(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s2.endsWith("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(!s2.endsWith("hi"), "this is a clue")
| || | |
| || true "hi"
| |"ScalaTest hi"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s3 contains \"hi\"") {
assert(s3 contains "hi", "this is a clue")
assert(s3.contains("hi"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s3 contains \"hello\"") {
val e1 = intercept[TestFailedException] {
assert(s3 contains "hello", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(s3 contains "hello", "this is a clue")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(s3.contains("hello"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(s3.contains("hello"), "this is a clue")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 contains 2") {
assert(ci2 contains 2, "this is a clue")
assert(ci2.contains(2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(ci1 contains 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(ci1 contains 5, "this is a clue")
| | | |
| 123 false 5
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestFailedException] {
assert(ci1.contains(5), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(ci1.contains(5), "this is a clue")
| | | |
| 123 false 5
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.contains(\"hello\")") {
assert(!s3.contains("hello"), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s3.contains(\"hi\")") {
val e1 = intercept[TestFailedException] {
assert(!s3.contains("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(!s3.contains("hi"), "this is a clue")
| || | |
| || true "hi"
| |"Say hi to ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1 contains 2") {
assert(l1 contains 2, "this is a clue")
assert(l1.contains(2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(l1 contains 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(l1 contains 5, "this is a clue")
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(l1.contains(5), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(l1.contains(5), "this is a clue")
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(l1 contains 5)") {
assert(!(l1 contains 5), "this is a clue")
assert(!l1.contains(5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1 contains 2)") {
val e1 = intercept[TestFailedException] {
assert(!(l1 contains 2), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assert(!(l1 contains 2), "this is a clue")
| | | | |
| | | true 2
| | List(1, 2, 3)
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestFailedException] {
assert(!l1.contains(2), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assert(!l1.contains(2), "this is a clue")
| || | |
| || true 2
| |List(1, 2, 3)
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check m1 contains 2") {
assert(m1 contains 2, "this is a clue")
assert(m1.contains(2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check m1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(m1 contains 5, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(m1 contains 5, "this is a clue")
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(m1.contains(5), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assert(m1.contains(5), "this is a clue")
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(m1 contains 5)") {
assert(!(m1 contains 5), "this is a clue")
assert(!m1.contains(5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(m1 contains 2)") {
val e1 = intercept[TestFailedException] {
assert(!(m1 contains 2), "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(!(m1 contains 2), "this is a clue")
| | | | |
| | | true 2
| | $m1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestFailedException] {
assert(!m1.contains(2), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assert(!m1.contains(2), "this is a clue")
| || | |
| || true 2
| |$m1Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ct1 contains 8") {
assert(ct1 contains 8, "this is a clue")
assert(ct1.contains(8), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ct1 contains 5") {
val e1 = intercept[TestFailedException] {
assert(ct1 contains 5, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(ct1 contains 5, "this is a clue")
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ct1.contains(5), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assert(ct1.contains(5), "this is a clue")
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ct1.contains(5)") {
assert(!ct1.contains(5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ct1.contains(8)") {
val e1 = intercept[TestFailedException] {
assert(!ct1.contains(8), "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(!ct1.contains(8), "this is a clue")
| || | |
| || true 8
| |$ct1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 eq ci3") {
assert(ci1 eq ci3, "this is a clue")
assert(ci1.eq(ci3), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 eq ci2") {
val e1 = intercept[TestFailedException] {
assert(ci1 eq ci2, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(ci1 eq ci2, "this is a clue")
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ci1.eq(ci2), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assert(ci1.eq(ci2), "this is a clue")
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.eq(ci2)") {
assert(!ci1.eq(ci2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ci1.eq(ci3)") {
val e = intercept[TestFailedException] {
assert(!ci1.eq(ci3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!ci1.eq(ci3), "this is a clue")
| || | |
| |$ci1Str | $ci3Str
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 ne ci2") {
assert(ci1 ne ci2, "this is a clue")
assert(ci1.ne(ci2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check ci1 ne ci3") {
val e1 = intercept[TestFailedException] {
assert(ci1 ne ci3, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assert(ci1 ne ci3, "this is a clue")
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestFailedException] {
assert(ci1.ne(ci3), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assert(ci1.ne(ci3), "this is a clue")
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.ne(ci3)") {
assert(!ci1.ne(ci3), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !ci1.ne(ci2)") {
val e = intercept[TestFailedException] {
assert(!ci1.ne(ci2), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!ci1.ne(ci2), "this is a clue")
| || | |
| |123 | 321
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s4.isEmpty") {
assert(s4.isEmpty, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s3.isEmpty") {
val e = intercept[TestFailedException] {
assert(s3.isEmpty, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(s3.isEmpty, "this is a clue")
| | |
| | false
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !s3.isEmpty") {
assert(!s3.isEmpty, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s4.isEmpty") {
val e = intercept[TestFailedException] {
assert(!s4.isEmpty, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!s4.isEmpty, "this is a clue")
| || |
| |"" true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l2.isEmpty") {
assert(l2.isEmpty, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isEmpty") {
val e = intercept[TestFailedException] {
assert(l1.isEmpty, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.isEmpty, "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isEmpty") {
assert(!l1.isEmpty, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l2.isEmpty") {
val e = intercept[TestFailedException] {
assert(!l2.isEmpty, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!l2.isEmpty, "this is a clue")
| || |
| || true
| |$l2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.isInstanceOf[String]") {
assert(s1.isInstanceOf[String], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isInstanceOf[String]") {
val e = intercept[TestFailedException] {
assert(l1.isInstanceOf[String], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.isInstanceOf[String], "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l1.isInstanceOf[List[Int]]") {
assert(l1.isInstanceOf[List[Int]], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.isInstanceOf[List[Int]]") {
val e = intercept[TestFailedException] {
assert(s1.isInstanceOf[List[Int]], "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(s1.isInstanceOf[List[Int]], "this is a clue")
| | |
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check date.isInstanceOf[Date]") {
assert(date.isInstanceOf[Date], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.isInstanceOf[Date]") {
val e = intercept[TestFailedException] {
assert(l1.isInstanceOf[Date], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.isInstanceOf[Date], "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isInstanceOf[String]") {
assert(!l1.isInstanceOf[String], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !s1.isInstanceOf[String]") {
val e = intercept[TestFailedException] {
assert(!s1.isInstanceOf[String], "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!s1.isInstanceOf[String], "this is a clue")
| || |
| || true
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !s1.isInstanceOf[List[Int]]") {
assert(!s1.isInstanceOf[List[Int]], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l1.isInstanceOf[List[Int]]") {
val e = intercept[TestFailedException] {
assert(!l1.isInstanceOf[List[Int]], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!l1.isInstanceOf[List[Int]], "this is a clue")
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !l1.isInstanceOf[Date]") {
assert(!l1.isInstanceOf[Date], "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !date.isInstanceOf[Date]") {
val e = intercept[TestFailedException] {
assert(!date.isInstanceOf[Date], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!date.isInstanceOf[Date], "this is a clue")
| || |
| || true
| |$date
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.length == 9") {
assert(s1.length == 12, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.length == 10") {
val e = intercept[TestFailedException] {
assert(s1.length == 10, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(s1.length == 10, "this is a clue")
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.length == 3") {
assert(l1.length == 3, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.length == 10") {
val e = intercept[TestFailedException] {
assert(l1.length == 10, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.length == 10, "this is a clue")
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.length == 10)") {
assert(!(s1.length == 10), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(s1.length == 9)") {
val e = intercept[TestFailedException] {
assert(!(s1.length == 12), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!(s1.length == 12), "this is a clue")
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.length == 2)") {
assert(!(l1.length == 2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1.length == 9)") {
val e = intercept[TestFailedException] {
assert(!(l1.length == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!(l1.length == 3), "this is a clue")
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check s1.size == 9") {
assert(s1.size == 12, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check s1.size == 10") {
val e = intercept[TestFailedException] {
assert(s1.size == 10, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(s1.size == 10, "this is a clue")
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.size == 3") {
assert(l1.size == 3, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.size == 10") {
val e = intercept[TestFailedException] {
assert(l1.size == 10, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.size == 10, "this is a clue")
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.size == 10)") {
assert(!(s1.size == 10), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(s1.size == 9)") {
val e = intercept[TestFailedException] {
assert(!(s1.size == 12), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(!(s1.size == 12), "this is a clue")
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.size == 2)") {
assert(!(l1.size == 2), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !(l1.size == 9) ") {
val e = intercept[TestFailedException] {
assert(!(l1.size == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!(l1.size == 3), "this is a clue")
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check l1.exists(_ == 3)") {
assert(l1.exists(_ == 3), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.exists(_ == 5) ") {
val e = intercept[TestFailedException] {
assert(l1.exists(_ == 5), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.exists(_ == 5), "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.exists(_ == 5)") {
assert(!l1.exists(_ == 5), "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check !l1.exists(_ == 3)") {
val e = intercept[TestFailedException] {
assert(!l1.exists(_ == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(!l1.exists(_ == 3), "this is a clue")
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l1.exists(_ > 3)") {
val e = intercept[TestFailedException] {
assert(l1.exists(_ > 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l1.exists(_ > 3), "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l3.exists(_.isEmpty)") {
val e = intercept[TestFailedException] {
assert(l3.exists(_.isEmpty), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assert(l3.exists(_.isEmpty), "this is a clue")
| | |
| | false
| $l3Str
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestFailedException with correct message and stack depth when is used to check l3.exists(false)") {
val e = intercept[TestFailedException] {
assert(ci1.exists(321), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(ci1.exists(321), "this is a clue")
| | | |
| 123 false 321
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when used to check woof { meow(y = 5) } == \"woof\"") {
assert(woof { meow(y = 5) } == "woof", "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check woof { meow(y = 5) } == \"meow\"") {
val e = intercept[TestFailedException] {
assert(woof { meow(y = 5) } == "meow", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(woof { meow(y = 5) } == "meow", "this is a clue")
| | | |
| "woof" | "meow"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when used to check multiline assert((b == a + 2) && (b - 2 <= a)) ") {
assert((b == a + 2) && (b - 2 <=
a), "this is a clue")
}
it("should throw friend message when used to check multiline assert((b == a + 2) && (b - 1 <= a))") {
val e = intercept[TestFailedException] {
assert((b == a + 2) && (b - 1 <=
a), "this is a clue")
}
e.message shouldBe Some("5 equaled 5, but 4 was not less than or equal to 3 this is a clue")
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
}
it("should do nothing when a block of code that evaluates to true is passed in") {
assert({
val a = 1
val b = 2
val c = a + b
a < b || c == a + b
}, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when a block of code that evaluates to false is passed") {
val e = intercept[TestFailedException] {
assert({ val a = 1; val b = 2; val c = a + b; a > b || c == b * b }, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert({ val a = 1; val b = 2; val c = a + b; a > b || c == b * b }, "this is a clue")
| | | | | | | | | |
| 1 | 2 | 3 | 2 4 2
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should fallback to BooleanMacro when a block of code > 1 line is passed in ") {
val e = intercept[TestFailedException] {
assert({
val a = 1
val b = 2
val c = a + b
a > b || c == b * b }, "this is a clue")
}
e.message should be (
Some(
"""{
| val a: Int = 1;
| val b: Int = 2;
| val c: Int = a.+(b);
| a.>(b).||(c.==(b.*(b)))
|} was false this is a clue""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 17))
}
it("should do nothing when used to check <person>Dude</person> == <person>Dude</person>") {
assert(<person>Dude</person> == <person>Dude</person>, "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check <person>Dude</person> == <person>Mary</person>") {
val e = intercept[TestFailedException] {
assert(<person>Dude</person> == <person>Mary</person>, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(<person>Dude</person> == <person>Mary</person>, "this is a clue")
| | | |
| | | <person>Mary</person>
| | false
| <person>Dude</person>
|""".stripMargin
)
)
}
it("should compile when used with org == xxx that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "test"
|assert(org == "test", "this is a clue")
""".stripMargin)
}
it("should compile when used with org === xxx that shadow org.scalactic") {
assertCompiles(
"""
|val org = "test"
|assert(org === "test", "this is a clue")
""".stripMargin)
}
it("should compile when used with org === xxx with TypeCheckedTripleEquals that shadow org.scalactic") {
assertCompiles(
"""
|class TestSpec extends FunSpec with org.scalactic.TypeCheckedTripleEquals {
| it("testing here") {
| val org = "test"
| assert(org === "test", "this is a clue")
| }
|}
""".stripMargin)
}
it("should compile when used with org.aCustomMethod that shadow org.scalactic") {
assertCompiles(
"""
|class Test {
| def aCustomMethod: Boolean = true
|}
|val org = new Test
|assert(org.aCustomMethod, "this is a clue")
""".stripMargin)
}
it("should compile when used with !org that shadow org.scalactic") {
assertCompiles(
"""
|val org = false
|assert(!org, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.isEmpty that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.isEmpty, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.isInstanceOf that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.isInstanceOf[String], "this is a clue")
""".stripMargin)
}
it("should compile when used with org.size == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = Array.empty[String]
|assert(org.size == 0, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.length == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assert(org.length == 0, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.exists(_ == 'b') that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "abc"
|assert(org.exists(_ == 'b'), "this is a clue")
""".stripMargin)
}
it("should do nothing when is used to check new String(\"test\") != \"test\"") {
assert(new String("test") == "test", "this is a clue")
}
it("should throw TestFailedException with correct message and stack depth when is used to check new String(\"test\") != \"testing\"") {
val e = intercept[TestFailedException] {
assert(new String("test") == "testing", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assert(new String("test") == "testing", "this is a clue")
| | | |
| "test" | "testing"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
}
describe("The assume(boolean) method") {
it("should do nothing when is used to check a == 3") {
assume(a == 3)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 5") {
val e = intercept[TestCanceledException] {
assume(a == 5)
}
e.message should be (
Some(
"""
|
|assume(a == 5)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 == b") {
assume(5 == b)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 == b") {
val e = intercept[TestCanceledException] {
assume(3 == b)
}
e.message should be (
Some(
"""
|
|assume(3 == b)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a != 5") {
assume(a != 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a != 3") {
val e = intercept[TestCanceledException] {
assume(a != 3)
}
e.message should be (
Some(
"""
|
|assume(a != 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 != b") {
assume(3 != b)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 != b") {
val e = intercept[TestCanceledException] {
assume(5 != b)
}
e.message should be (
Some(
"""
|
|assume(5 != b)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 == 3") {
assume(3 == 3)
}
it("should throw TestCanceledException with message that contains the original code and correct stack depth when is used to check 3 == 5") {
// This is because the compiler simply pass the false boolean literal
// to the macro, can't find a way to get the 3 == 5 literal.
val e1 = intercept[TestCanceledException] {
assume(3 == 5)
}
e1.message should be (
Some(
"""
|
|assume(3 == 5)
| |
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == b") {
val e = intercept[TestCanceledException] {
assume(a == b)
}
e.message should be (
Some(
"""
|
|assume(a == b)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check c == null") {
val e = intercept[TestCanceledException] {
assume(c == null)
}
e.message should be (
Some(
"""
|
|assume(c == null)
| | | |
| | | null
| | false
| "8"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check null == c") {
val e = intercept[TestCanceledException] {
assume(null == c)
}
e.message should be (
Some(
"""
|
|assume(null == c)
| | | |
| null | "8"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 != a") {
val e = intercept[TestCanceledException] {
assume(3 != a)
}
e.message should be (
Some(
"""
|
|assume(3 != a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 != a") {
assume(5 != a)
}
it("should do nothing when is used to check a > 2") {
assume(a > 2)
}
it("should do nothing when is used to check 5 > a") {
assume(5 > a)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a > 3") {
val e = intercept[TestCanceledException] {
assume(a > 3)
}
e.message should be (
Some(
"""
|
|assume(a > 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 > a") {
val e = intercept[TestCanceledException] {
assume(3 > a)
}
e.message should be (
Some(
"""
|
|assume(3 > a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a >= 3") {
assume(a >= 3)
}
it("should do nothing when is used to check 3 >= a") {
assume(3 >= a)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a >= 4") {
val e = intercept[TestCanceledException] {
assume(a >= 4)
}
e.message should be (
Some(
"""
|
|assume(a >= 4)
| | | |
| 3 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 2 >= a") {
val e = intercept[TestCanceledException] {
assume(2 >= a)
}
e.message should be (
Some(
"""
|
|assume(2 >= a)
| | | |
| 2 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b < 6") {
assume(b < 6)
}
it("should do nothing when is used to check 3 < b") {
assume(3 < b)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check b < 5") {
val e = intercept[TestCanceledException] {
assume(b < 5)
}
e.message should be (
Some(
"""
|
|assume(b < 5)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 < b") {
val e = intercept[TestCanceledException] {
assume(5 < b)
}
e.message should be (
Some(
"""
|
|assume(5 < b)
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b <= 5") {
assume(b <= 5)
}
it("should do nothing when is used to check 5 <= b") {
assume(5 <= b)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check b <= 4") {
val e = intercept[TestCanceledException] {
assume(b <= 4)
}
e.message should be (
Some(
"""
|
|assume(b <= 4)
| | | |
| 5 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 6 <= b") {
val e = intercept[TestCanceledException] {
assume(6 <= b)
}
e.message should be (
Some(
"""
|
|assume(6 <= b)
| | | |
| 6 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check bob == \"bob\"") {
assume(bob == "bob")
}
it("should do nothing when is used to check bob != \"alice\"") {
assume(bob != "alice")
}
it("should do nothing when is used to check alice == \"alice\"") {
assume(alice == "alice")
}
it("should do nothing when is used to check alice != \"bob\"") {
assume(alice != "bob")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check bob == \"alice\"") {
val e = intercept[TestCanceledException] {
assume(bob == "alice")
}
e.message should be (
Some(
"""
|
|assume(bob == "alice")
| | | |
| | | "alice"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check bob != \"bob\"") {
val e = intercept[TestCanceledException] {
assume(bob != "bob")
}
e.message should be (
Some(
"""
|
|assume(bob != "bob")
| | | |
| | | "bob"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check alice == \"bob\"") {
val e = intercept[TestCanceledException] {
assume(alice == "bob")
}
e.message should be (
Some(
"""
|
|assume(alice == "bob")
| | | |
| | | "bob"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check alice != \"alice\"") {
val e = intercept[TestCanceledException] {
assume(alice != "alice")
}
e.message should be (
Some(
"""
|
|assume(alice != "alice")
| | | |
| | | "alice"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check a === 3") {
assume(a === 3)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a === 5 ") {
val e = intercept[TestCanceledException] {
assume(a === 5)
}
e.message should be (
Some(
"""
|
|assume(a === 5)
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 === a") {
assume(3 === a)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 === a") {
val e = intercept[TestCanceledException] {
assume(5 === a)
}
e.message should be (
Some(
"""
|
|assume(5 === a)
| | | |
| 5 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a !== 5") {
assume(a !== 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a !== 3") {
val e = intercept[TestCanceledException] {
assume(a !== 3)
}
e.message should be (
Some(
"""
|
|assume(a !== 3)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 !== a") {
assume(5 !== a)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 !== a") {
val e = intercept[TestCanceledException] {
assume(3 !== a)
}
e.message should be (
Some(
"""
|
|assume(3 !== a)
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 && b == 5") {
assume(a == 3 && b == 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 3 && b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 3 && b == 6)
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 && b == 5") {
val e = intercept[TestCanceledException] {
assume(a == 2 && b == 5)
}
e.message should be (
Some(
"""
|
|assume(a == 2 && b == 5)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 && b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 && b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 2 && b == 6)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 & b == 5") {
assume(a == 3 & b == 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 & b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 3 & b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 3 & b == 6)
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 & b == 5") {
val e = intercept[TestCanceledException] {
assume(a == 2 & b == 5)
}
e.message should be (
Some(
"""
|
|assume(a == 2 & b == 5)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 & b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 & b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 2 & b == 6)
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 || b == 5") {
assume(a == 3 || b == 5)
}
it("should do nothing when is used to check a == 3 || b == 6") {
assume(a == 3 || b == 6)
}
it("should do nothing when is used to check a == 2 || b == 5") {
assume(a == 2 || b == 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 || b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 || b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 2 || b == 6)
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 | b == 5") {
assume(a == 3 | b == 5)
}
it("should do nothing when is used to check a == 3 | b == 6") {
assume(a == 3 | b == 6)
}
it("should do nothing when is used to check a == 2 | b == 5") {
assume(a == 2 | b == 5)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 | b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 | b == 6)
}
e.message should be (
Some(
"""
|
|assume(a == 2 | b == 6)
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 && (b == 5 && b > 3)") {
assume(a == 3 && (b == 5 && b > 3))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && (b == 5 && b > 5)") {
val e = intercept[TestCanceledException] {
assume(a == 3 && (b == 5 && b > 5))
}
e.message should be (
Some(
"""
|
|assume(a == 3 && (b == 5 && b > 5))
| | | | | | | | | | | |
| 3 | 3 | 5 | 5 | 5 | 5
| true false true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(a == 5)") {
assume(!(a == 5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(a == 3)") {
val e = intercept[TestCanceledException] {
assume(!(a == 3))
}
e.message should be (
Some(
"""
|
|assume(!(a == 3))
| | | | |
| | 3 | 3
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && !(b == 5)") {
val e = intercept[TestCanceledException] {
assume(a == 3 && !(b == 5))
}
e.message should be (
Some(
"""
|
|assume(a == 3 && !(b == 5))
| | | | | | | | |
| 3 | 3 | | 5 | 5
| true | | true
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check (a == 3) == (b == 5)") {
assume((a == 3) == (b == 5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check (a == 3) == (b != 5)") {
val e = intercept[TestCanceledException] {
assume((a == 3) == (b != 5))
}
e.message should be (
Some(
"""
|
|assume((a == 3) == (b != 5))
| | | | | | | |
| 3 | 3 | 5 | 5
| true false false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should short-circuit && when first condition was false") {
val s = new Stateful
intercept[TestCanceledException] {
assume(a == 5 && s.changeState)
}
s.state should be (false)
}
it("should short-circuit & when first condition was false") {
val s = new Stateful
intercept[TestCanceledException] {
assume(a == 5 & s.changeState)
}
s.state should be (false)
}
it("should short-circuit || when first condition was true") {
val s = new Stateful
assume(a == 3 || s.changeState)
s.state should be (false)
}
it("should short-circuit | when first condition was true") {
val s = new Stateful
assume(a == 3 | s.changeState)
s.state should be (false)
}
it("should do nothing when it is used to check a == 3 && { println(\"hi\"); b == 5} ") {
assume(a == 3 && { println("hi"); b == 5})
}
it("should throw TestCanceledException with correct message and stack depth when is usesd to check a == 3 && { println(\"hi\"); b == 3}") {
val e = intercept[TestCanceledException] {
assume(a == 3 && { println("hi"); b == 3})
}
e.message should be (
Some(
"""
|
|assume(a == 3 && { println("hi"); b == 3})
| | | | | | | |
| 3 | 3 false 5 | 3
| true false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when it is used to check { println(\"hi\"); b == 5} && a == 3") {
assume({ println("hi"); b == 5} && a == 3)
}
it("should throw TestCanceledException with correct message and stack depth when is usesd to check { println(\"hi\"); b == 5} && a == 5") {
val e = intercept[TestCanceledException] {
assume({ println("hi"); b == 5} && a == 5)
}
e.message should be (
Some(
"""
|
|assume({ println("hi"); b == 5} && a == 5)
| | | | | | | |
| 5 | 5 | 3 | 5
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should preserve side effects when Apply with single argument is passed in") {
assume(neverRuns1(sys.error("Sad times 1")))
}
it("should preserve side effects when Apply with 2 argument list is passed in") {
assume(neverRuns2(sys.error("Sad times 2"))(0))
}
it("should preserve side effects when typed Apply with 2 argument list is passed in") {
assume(neverRuns3(sys.error("Sad times 3"))(0))
}
it("should do nothing when is used to check s1 startsWith \"hi\"") {
assume(s1 startsWith "hi")
assume(s1.startsWith("hi"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s2 startsWith \"hi\"") {
val e1 = intercept[TestCanceledException] {
assume(s2 startsWith "hi")
}
e1.message should be (
Some(
"""
|
|assume(s2 startsWith "hi")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s2.startsWith("hi"))
}
e2.message should be (
Some(
"""
|
|assume(s2.startsWith("hi"))
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci1 startsWith 1") {
assume(ci1 startsWith 1)
assume(ci1.startsWith(1))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci2 startsWith 1") {
val e1 = intercept[TestCanceledException] {
assume(ci2 startsWith 1)
}
e1.message should be (
Some(
"""
|
|assume(ci2 startsWith 1)
| | | |
| 321 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci2.startsWith(1))
}
e2.message should be (
Some(
"""
|
|assume(ci2.startsWith(1))
| | | |
| 321 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s2.startsWith(\"hi\")") {
assume(!s2.startsWith("hi"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s1.startsWith(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s1.startsWith("hi"))
}
e1.message should be (
Some(
"""
|
|assume(!s1.startsWith("hi"))
| || | |
| || true "hi"
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s2 endsWith \"hi\"") {
assume(s2 endsWith "hi")
assume(s2.endsWith("hi"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1 endsWith \"hi\"") {
val e1 = intercept[TestCanceledException] {
assume(s1 endsWith "hi")
}
e1.message should be (
Some(
"""
|
|assume(s1 endsWith "hi")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s1.endsWith("hi"))
}
e2.message should be (
Some(
"""
|
|assume(s1.endsWith("hi"))
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 endsWith 1") {
assume(ci2 endsWith 1)
assume(ci2.endsWith(1))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 endsWith 1") {
val e1 = intercept[TestCanceledException] {
assume(ci1 endsWith 1)
}
e1.message should be (
Some(
"""
|
|assume(ci1 endsWith 1)
| | | |
| 123 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci1.endsWith(1))
}
e2.message should be (
Some(
"""
|
|assume(ci1.endsWith(1))
| | | |
| 123 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.endsWith(\"hi\")") {
assume(!s1.endsWith("hi"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s2.endsWith(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s2.endsWith("hi"))
}
e1.message should be (
Some(
"""
|
|assume(!s2.endsWith("hi"))
| || | |
| || true "hi"
| |"ScalaTest hi"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s3 contains \"hi\"") {
assume(s3 contains "hi")
assume(s3.contains("hi"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s3 contains \"hello\"") {
val e1 = intercept[TestCanceledException] {
assume(s3 contains "hello")
}
e1.message should be (
Some(
"""
|
|assume(s3 contains "hello")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s3.contains("hello"))
}
e2.message should be (
Some(
"""
|
|assume(s3.contains("hello"))
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 contains 2") {
assume(ci2 contains 2)
assume(ci2.contains(2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(ci1 contains 5)
}
e1.message should be (
Some(
"""
|
|assume(ci1 contains 5)
| | | |
| 123 false 5
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci1.contains(5))
}
e2.message should be (
Some(
"""
|
|assume(ci1.contains(5))
| | | |
| 123 false 5
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.contains(\"hello\")") {
assume(!s3.contains("hello"))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s3.contains(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s3.contains("hi"))
}
e1.message should be (
Some(
"""
|
|assume(!s3.contains("hi"))
| || | |
| || true "hi"
| |"Say hi to ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1 contains 2") {
assume(l1 contains 2)
assume(l1.contains(2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(l1 contains 5)
}
e1.message should be (
Some(
"""
|
|assume(l1 contains 5)
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(l1.contains(5))
}
e2.message should be (
Some(
"""
|
|assume(l1.contains(5))
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(l1 contains 5)") {
assume(!(l1 contains 5))
assume(!l1.contains(5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1 contains 2)") {
val e1 = intercept[TestCanceledException] {
assume(!(l1 contains 2))
}
e1.message should be (
Some(
"""
|
|assume(!(l1 contains 2))
| | | | |
| | | true 2
| | List(1, 2, 3)
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestCanceledException] {
assume(!l1.contains(2))
}
e2.message should be (
Some(
"""
|
|assume(!l1.contains(2))
| || | |
| || true 2
| |List(1, 2, 3)
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check m1 contains 2") {
assume(m1 contains 2)
assume(m1.contains(2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check m1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(m1 contains 5)
}
e1.message should be (
Some(
s"""
|
|assume(m1 contains 5)
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(m1.contains(5))
}
e2.message should be (
Some(
s"""
|
|assume(m1.contains(5))
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(m1 contains 5)") {
assume(!(m1 contains 5))
assume(!m1.contains(5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(m1 contains 2)") {
val e1 = intercept[TestCanceledException] {
assume(!(m1 contains 2))
}
e1.message should be (
Some(
s"""
|
|assume(!(m1 contains 2))
| | | | |
| | | true 2
| | $m1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestCanceledException] {
assume(!m1.contains(2))
}
e2.message should be (
Some(
s"""
|
|assume(!m1.contains(2))
| || | |
| || true 2
| |$m1Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ct1 contains 8") {
assume(ct1 contains 8)
assume(ct1.contains(8))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ct1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(ct1 contains 5)
}
e1.message should be (
Some(
s"""
|
|assume(ct1 contains 5)
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ct1.contains(5))
}
e2.message should be (
Some(
s"""
|
|assume(ct1.contains(5))
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ct1.contains(5)") {
assume(!ct1.contains(5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ct1.contains(8)") {
val e1 = intercept[TestCanceledException] {
assume(!ct1.contains(8))
}
e1.message should be (
Some(
s"""
|
|assume(!ct1.contains(8))
| || | |
| || true 8
| |$ct1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 eq ci3") {
assume(ci1 eq ci3)
assume(ci1.eq(ci3))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 eq ci2") {
val e1 = intercept[TestCanceledException] {
assume(ci1 eq ci2)
}
e1.message should be (
Some(
s"""
|
|assume(ci1 eq ci2)
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ci1.eq(ci2))
}
e2.message should be (
Some(
s"""
|
|assume(ci1.eq(ci2))
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.eq(ci2)") {
assume(!ci1.eq(ci2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ci1.eq(ci3)") {
val e = intercept[TestCanceledException] {
assume(!ci1.eq(ci3))
}
e.message should be (
Some(
s"""
|
|assume(!ci1.eq(ci3))
| || | |
| |$ci1Str | $ci3Str
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 ne ci2") {
assume(ci1 ne ci2)
assume(ci1.ne(ci2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 ne ci3") {
val e1 = intercept[TestCanceledException] {
assume(ci1 ne ci3)
}
e1.message should be (
Some(
s"""
|
|assume(ci1 ne ci3)
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ci1.ne(ci3))
}
e2.message should be (
Some(
s"""
|
|assume(ci1.ne(ci3))
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.ne(ci3)") {
assume(!ci1.ne(ci3))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ci1.ne(ci2)") {
val e = intercept[TestCanceledException] {
assume(!ci1.ne(ci2))
}
e.message should be (
Some(
"""
|
|assume(!ci1.ne(ci2))
| || | |
| |123 | 321
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s4.isEmpty") {
assume(s4.isEmpty)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s3.isEmpty") {
val e = intercept[TestCanceledException] {
assume(s3.isEmpty)
}
e.message should be (
Some(
"""
|
|assume(s3.isEmpty)
| | |
| | false
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !s3.isEmpty") {
assume(!s3.isEmpty)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s4.isEmpty") {
val e = intercept[TestCanceledException] {
assume(!s4.isEmpty)
}
e.message should be (
Some(
"""
|
|assume(!s4.isEmpty)
| || |
| |"" true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l2.isEmpty") {
assume(l2.isEmpty)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isEmpty") {
val e = intercept[TestCanceledException] {
assume(l1.isEmpty)
}
e.message should be (
Some(
s"""
|
|assume(l1.isEmpty)
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isEmpty") {
assume(!l1.isEmpty)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l2.isEmpty") {
val e = intercept[TestCanceledException] {
assume(!l2.isEmpty)
}
e.message should be (
Some(
s"""
|
|assume(!l2.isEmpty)
| || |
| || true
| |$l2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.isInstanceOf[String]") {
assume(s1.isInstanceOf[String])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isInstanceOf[String]") {
val e = intercept[TestCanceledException] {
assume(l1.isInstanceOf[String])
}
e.message should be (
Some(
s"""
|
|assume(l1.isInstanceOf[String])
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l1.isInstanceOf[List[Int]]") {
assume(l1.isInstanceOf[List[Int]])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.isInstanceOf[List[Int]]") {
val e = intercept[TestCanceledException] {
assume(s1.isInstanceOf[List[Int]])
}
e.message should be (
Some(
"""
|
|assume(s1.isInstanceOf[List[Int]])
| | |
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check date.isInstanceOf[Date]") {
assume(date.isInstanceOf[Date])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isInstanceOf[Date]") {
val e = intercept[TestCanceledException] {
assume(l1.isInstanceOf[Date])
}
e.message should be (
Some(
s"""
|
|assume(l1.isInstanceOf[Date])
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isInstanceOf[String]") {
assume(!l1.isInstanceOf[String])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s1.isInstanceOf[String]") {
val e = intercept[TestCanceledException] {
assume(!s1.isInstanceOf[String])
}
e.message should be (
Some(
"""
|
|assume(!s1.isInstanceOf[String])
| || |
| || true
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !s1.isInstanceOf[List[Int]]") {
assume(!s1.isInstanceOf[List[Int]])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l1.isInstanceOf[List[Int]]") {
val e = intercept[TestCanceledException] {
assume(!l1.isInstanceOf[List[Int]])
}
e.message should be (
Some(
s"""
|
|assume(!l1.isInstanceOf[List[Int]])
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !l1.isInstanceOf[Date]") {
assume(!l1.isInstanceOf[Date])
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !date.isInstanceOf[Date]") {
val e = intercept[TestCanceledException] {
assume(!date.isInstanceOf[Date])
}
e.message should be (
Some(
s"""
|
|assume(!date.isInstanceOf[Date])
| || |
| || true
| |$date
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.length == 9") {
assume(s1.length == 12)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.length == 10") {
val e = intercept[TestCanceledException] {
assume(s1.length == 10)
}
e.message should be (
Some(
"""
|
|assume(s1.length == 10)
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.length == 3") {
assume(l1.length == 3)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.length == 10") {
val e = intercept[TestCanceledException] {
assume(l1.length == 10)
}
e.message should be (
Some(
s"""
|
|assume(l1.length == 10)
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.length == 10)") {
assume(!(s1.length == 10))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(s1.length == 9)") {
val e = intercept[TestCanceledException] {
assume(!(s1.length == 12))
}
e.message should be (
Some(
"""
|
|assume(!(s1.length == 12))
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.length == 2)") {
assume(!(l1.length == 2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1.length == 9)") {
val e = intercept[TestCanceledException] {
assume(!(l1.length == 3))
}
e.message should be (
Some(
s"""
|
|assume(!(l1.length == 3))
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check s1.size == 9") {
assume(s1.size == 12)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.size == 10") {
val e = intercept[TestCanceledException] {
assume(s1.size == 10)
}
e.message should be (
Some(
"""
|
|assume(s1.size == 10)
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.size == 3") {
assume(l1.size == 3)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.size == 10") {
val e = intercept[TestCanceledException] {
assume(l1.size == 10)
}
e.message should be (
Some(
s"""
|
|assume(l1.size == 10)
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.size == 10)") {
assume(!(s1.size == 10))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(s1.size == 9)") {
val e = intercept[TestCanceledException] {
assume(!(s1.size == 12))
}
e.message should be (
Some(
"""
|
|assume(!(s1.size == 12))
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.size == 2)") {
assume(!(l1.size == 2))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1.size == 9) ") {
val e = intercept[TestCanceledException] {
assume(!(l1.size == 3))
}
e.message should be (
Some(
s"""
|
|assume(!(l1.size == 3))
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check l1.exists(_ == 3)") {
assume(l1.exists(_ == 3))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.exists(_ == 5) ") {
val e = intercept[TestCanceledException] {
assume(l1.exists(_ == 5))
}
e.message should be (
Some(
s"""
|
|assume(l1.exists(_ == 5))
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.exists(_ == 5)") {
assume(!l1.exists(_ == 5))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l1.exists(_ == 3)") {
val e = intercept[TestCanceledException] {
assume(!l1.exists(_ == 3))
}
e.message should be (
Some(
s"""
|
|assume(!l1.exists(_ == 3))
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.exists(_ > 3)") {
val e = intercept[TestCanceledException] {
assume(l1.exists(_ > 3))
}
e.message should be (
Some(
s"""
|
|assume(l1.exists(_ > 3))
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l3.exists(_.isEmpty)") {
val e = intercept[TestCanceledException] {
assume(l3.exists(_.isEmpty))
}
e.message should be (
Some(
s"""
|
|assume(l3.exists(_.isEmpty))
| | |
| | false
| $l3Str
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l3.exists(false)") {
val e = intercept[TestCanceledException] {
assume(ci1.exists(321))
}
e.message should be (
Some(
"""
|
|assume(ci1.exists(321))
| | | |
| 123 false 321
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when used to check woof { meow(y = 5) } == \"woof\"") {
assume(woof { meow(y = 5) } == "woof")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check woof { meow(y = 5) } == \"meow\"") {
val e = intercept[TestCanceledException] {
assume(woof { meow(y = 5) } == "meow")
}
e.message should be (
Some(
"""
|
|assume(woof { meow(y = 5) } == "meow")
| | | |
| "woof" | "meow"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when used to check multiline assert((b == a + 2) && (b - 2 <= a)) ") {
assume((b == a + 2) && (b - 2 <=
a))
}
it("should throw TestCanceledException with friend message when used to check multiline assert((b == a + 2) && (b - 1 <= a))") {
val e = intercept[TestCanceledException] {
assume((b == a + 2) && (b - 1 <=
a))
}
e.message shouldBe Some("5 equaled 5, but 4 was not less than or equal to 3")
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
}
it("should do nothing when a block of code that evaluates to true is passed in") {
assume {
val a = 1
val b = 2
val c = a + b
a < b || c == a + b
}
}
it("should throw TestCanceledException with correct message and stack depth when a block of code that evaluates to false is passed") {
val e = intercept[TestCanceledException] {
assume { val a = 1; val b = 2; val c = a + b; a > b || c == b * b }
}
e.message should be (
Some(
"""
|
|assume { val a = 1; val b = 2; val c = a + b; a > b || c == b * b }
| | | | | | | | | |
| 1 | 2 | 3 | 2 4 2
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should fallback to BooleanMacro when a block of code > 1 line is passed in ") {
val e = intercept[TestCanceledException] {
assume {
val a = 1
val b = 2
val c = a + b
a > b || c == b * b }
}
e.message should be (
Some(
"""{
| val a: Int = 1;
| val b: Int = 2;
| val c: Int = a.+(b);
| a.>(b).||(c.==(b.*(b)))
|} was false""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 17))
}
it("should do nothing when used to check <person>Dude</person> == <person>Dude</person>") {
assume(<person>Dude</person> == <person>Dude</person>)
}
it("should throw TestCanceledException with correct message and stack depth when is used to check <person>Dude</person> == <person>Mary</person>") {
val e = intercept[TestCanceledException] {
assume(<person>Dude</person> == <person>Mary</person>)
}
e.message should be (
Some(
"""
|
|assume(<person>Dude</person> == <person>Mary</person>)
| | | |
| | | <person>Mary</person>
| | false
| <person>Dude</person>
|""".stripMargin
)
)
}
it("should compile when used with org == xxx that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "test"
|assume(org == "test")
""".stripMargin)
}
it("should compile when used with org === xxx that shadow org.scalactic") {
assertCompiles(
"""
|val org = "test"
|assume(org === "test")
""".stripMargin)
}
it("should compile when used with org === xxx with TypeCheckedTripleEquals that shadow org.scalactic") {
assertCompiles(
"""
|class TestSpec extends FunSpec with org.scalactic.TypeCheckedTripleEquals {
| it("testing here") {
| val org = "test"
| assume(org === "test")
| }
|}
""".stripMargin)
}
it("should compile when used with org.aCustomMethod that shadow org.scalactic") {
assertCompiles(
"""
|class Test {
| def aCustomMethod: Boolean = true
|}
|val org = new Test
|assume(org.aCustomMethod)
""".stripMargin)
}
it("should compile when used with !org that shadow org.scalactic") {
assertCompiles(
"""
|val org = false
|assume(!org)
""".stripMargin)
}
it("should compile when used with org.isEmpty that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.isEmpty)
""".stripMargin)
}
it("should compile when used with org.isInstanceOf that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.isInstanceOf[String])
""".stripMargin)
}
it("should compile when used with org.size == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = Array.empty[String]
|assume(org.size == 0)
""".stripMargin)
}
it("should compile when used with org.length == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.length == 0)
""".stripMargin)
}
it("should compile when used with org.exists(_ == 'b') that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "abc"
|assume(org.exists(_ == 'b'))
""".stripMargin)
}
it("should do nothing when is used to check new String(\"test\") != \"test\"") {
assume(new String("test") == "test")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check new String(\"test\") != \"testing\"") {
val e = intercept[TestCanceledException] {
assume(new String("test") == "testing")
}
e.message should be (
Some(
"""
|
|assume(new String("test") == "testing")
| | | |
| "test" | "testing"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
}
describe("The assume(boolean, clue) method") {
it("should do nothing when is used to check a == 3") {
assume(a == 3, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 5") {
val e = intercept[TestCanceledException] {
assume(a == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 5, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 == b") {
assume(5 == b, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 == b") {
val e = intercept[TestCanceledException] {
assume(3 == b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(3 == b, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a != 5") {
assume(a != 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a != 3") {
val e = intercept[TestCanceledException] {
assume(a != 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a != 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 != b") {
assume(3 != b, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 != b") {
val e = intercept[TestCanceledException] {
assume(5 != b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(5 != b, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 == 3") {
assume(3 == 3, "this is a clue")
}
it("should throw TestCanceledException with message that contains the original code and correct stack depth when is used to check 3 == 5") {
// This is because the compiler simply pass the false boolean literal
// to the macro, can't find a way to get the 3 == 5 literal.
val e1 = intercept[TestCanceledException] {
assume(3 == 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(3 == 5, "this is a clue")
| |
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == b") {
val e = intercept[TestCanceledException] {
assume(a == b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == b, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check c == null") {
val e = intercept[TestCanceledException] {
assume(c == null, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(c == null, "this is a clue")
| | | |
| | | null
| | false
| "8"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check null == c") {
val e = intercept[TestCanceledException] {
assume(null == c, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(null == c, "this is a clue")
| | | |
| null | "8"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 != a") {
val e = intercept[TestCanceledException] {
assume(3 != a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(3 != a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 != a") {
assume(5 != a, "this is a clue")
}
it("should do nothing when is used to check a > 2") {
assume(a > 2, "this is a clue")
}
it("should do nothing when is used to check 5 > a") {
assume(5 > a, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a > 3") {
val e = intercept[TestCanceledException] {
assume(a > 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a > 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 > a") {
val e = intercept[TestCanceledException] {
assume(3 > a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(3 > a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a >= 3") {
assume(a >= 3, "this is a clue")
}
it("should do nothing when is used to check 3 >= a") {
assume(3 >= a, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a >= 4") {
val e = intercept[TestCanceledException] {
assume(a >= 4, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a >= 4, "this is a clue")
| | | |
| 3 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 2 >= a") {
val e = intercept[TestCanceledException] {
assume(2 >= a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(2 >= a, "this is a clue")
| | | |
| 2 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b < 6") {
assume(b < 6, "this is a clue")
}
it("should do nothing when is used to check 3 < b") {
assume(3 < b, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check b < 5") {
val e = intercept[TestCanceledException] {
assume(b < 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(b < 5, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 < b") {
val e = intercept[TestCanceledException] {
assume(5 < b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(5 < b, "this is a clue")
| | | |
| 5 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check b <= 5") {
assume(b <= 5, "this is a clue")
}
it("should do nothing when is used to check 5 <= b") {
assume(5 <= b, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check b <= 4") {
val e = intercept[TestCanceledException] {
assume(b <= 4, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(b <= 4, "this is a clue")
| | | |
| 5 | 4
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 6 <= b") {
val e = intercept[TestCanceledException] {
assume(6 <= b, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(6 <= b, "this is a clue")
| | | |
| 6 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check bob == \"bob\"") {
assume(bob == "bob", "this is a clue")
}
it("should do nothing when is used to check bob != \"alice\"") {
assume(bob != "alice", "this is a clue")
}
it("should do nothing when is used to check alice == \"alice\"") {
assume(alice == "alice", "this is a clue")
}
it("should do nothing when is used to check alice != \"bob\"") {
assume(alice != "bob", "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check bob == \"alice\"") {
val e = intercept[TestCanceledException] {
assume(bob == "alice", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(bob == "alice", "this is a clue")
| | | |
| | | "alice"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check bob != \"bob\"") {
val e = intercept[TestCanceledException] {
assume(bob != "bob", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(bob != "bob", "this is a clue")
| | | |
| | | "bob"
| | false
| "bob"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check alice == \"bob\"") {
val e = intercept[TestCanceledException] {
assume(alice == "bob", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(alice == "bob", "this is a clue")
| | | |
| | | "bob"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check alice != \"alice\"") {
val e = intercept[TestCanceledException] {
assume(alice != "alice", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(alice != "alice", "this is a clue")
| | | |
| | | "alice"
| | false
| "alice"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check a === 3") {
assume(a === 3, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a === 5 ") {
val e = intercept[TestCanceledException] {
assume(a === 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a === 5, "this is a clue")
| | | |
| 3 | 5
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 3 === a") {
assume(3 === a, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 5 === a") {
val e = intercept[TestCanceledException] {
assume(5 === a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(5 === a, "this is a clue")
| | | |
| 5 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a !== 5") {
assume(a !== 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a !== 3") {
val e = intercept[TestCanceledException] {
assume(a !== 3, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a !== 3, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check 5 !== a") {
assume(5 !== a, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check 3 !== a") {
val e = intercept[TestCanceledException] {
assume(3 !== a, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(3 !== a, "this is a clue")
| | | |
| 3 | 3
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 && b == 5") {
assume(a == 3 && b == 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 3 && b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 3 && b == 6, "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 && b == 5") {
val e = intercept[TestCanceledException] {
assume(a == 2 && b == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 && b == 5, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 && b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 && b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 && b == 6, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 & b == 5") {
assume(a == 3 & b == 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 & b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 3 & b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 3 & b == 6, "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 6
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 & b == 5") {
val e = intercept[TestCanceledException] {
assume(a == 2 & b == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 & b == 5, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 & b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 & b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 & b == 6, "this is a clue")
| | | |
| 3 | 2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check a == 3 || b == 5") {
assume(a == 3 || b == 5, "this is a clue")
}
it("should do nothing when is used to check a == 3 || b == 6") {
assume(a == 3 || b == 6, "this is a clue")
}
it("should do nothing when is used to check a == 2 || b == 5") {
assume(a == 2 || b == 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 || b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 || b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 || b == 6, "this is a clue")
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 | b == 5") {
assume(a == 3 | b == 5, "this is a clue")
}
it("should do nothing when is used to check a == 3 | b == 6") {
assume(a == 3 | b == 6, "this is a clue")
}
it("should do nothing when is used to check a == 2 | b == 5") {
assume(a == 2 | b == 5, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 2 | b == 6") {
val e = intercept[TestCanceledException] {
assume(a == 2 | b == 6, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 2 | b == 6, "this is a clue")
| | | | | | | |
| 3 | 2 | 5 | 6
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check a == 3 && (b == 5 && b > 3)") {
assume(a == 3 && (b == 5 && b > 3), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && (b == 5 && b > 5)") {
val e = intercept[TestCanceledException] {
assume(a == 3 && (b == 5 && b > 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 3 && (b == 5 && b > 5), "this is a clue")
| | | | | | | | | | | |
| 3 | 3 | 5 | 5 | 5 | 5
| true false true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(a == 5)") {
assume(!(a == 5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(a == 3)") {
val e = intercept[TestCanceledException] {
assume(!(a == 3), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!(a == 3), "this is a clue")
| | | | |
| | 3 | 3
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check a == 3 && !(b == 5)") {
val e = intercept[TestCanceledException] {
assume(a == 3 && !(b == 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 3 && !(b == 5), "this is a clue")
| | | | | | | | |
| 3 | 3 | | 5 | 5
| true | | true
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check (a == 3) == (b == 5)") {
assume((a == 3) == (b == 5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check (a == 3) == (b != 5)") {
val e = intercept[TestCanceledException] {
assume((a == 3) == (b != 5), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume((a == 3) == (b != 5), "this is a clue")
| | | | | | | |
| 3 | 3 | 5 | 5
| true false false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should short-circuit && when first condition was false") {
val s = new Stateful
intercept[TestCanceledException] {
assume(a == 5 && s.changeState, "this is a clue")
}
s.state should be (false)
}
it("should short-circuit & when first condition was false") {
val s = new Stateful
intercept[TestCanceledException] {
assume(a == 5 & s.changeState, "this is a clue")
}
s.state should be (false)
}
it("should short-circuit || when first condition was true") {
val s = new Stateful
assume(a == 3 || s.changeState, "this is a clue")
s.state should be (false)
}
it("should short-circuit | when first condition was true") {
val s = new Stateful
assume(a == 3 | s.changeState, "this is a clue")
s.state should be (false)
}
it("should do nothing when it is used to check a == 3 && { println(\"hi\"); b == 5} ") {
assume(a == 3 && { println("hi"); b == 5}, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is usesd to check a == 3 && { println(\"hi\"); b == 3}") {
val e = intercept[TestCanceledException] {
assume(a == 3 && { println("hi"); b == 3}, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(a == 3 && { println("hi"); b == 3}, "this is a clue")
| | | | | | | |
| 3 | 3 false 5 | 3
| true false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when it is used to check { println(\"hi\"); b == 5} && a == 3") {
assume({ println("hi"); b == 5} && a == 3, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is usesd to check { println(\"hi\"); b == 5} && a == 5") {
val e = intercept[TestCanceledException] {
assume({ println("hi"); b == 5} && a == 5, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume({ println("hi"); b == 5} && a == 5, "this is a clue")
| | | | | | | |
| 5 | 5 | 3 | 5
| true | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should preserve side effects when Apply with single argument is passed in") {
assume(neverRuns1(sys.error("Sad times 1")), "this is a clue")
}
it("should preserve side effects when Apply with 2 argument list is passed in") {
assume(neverRuns2(sys.error("Sad times 2"))(0), "this is a clue")
}
it("should preserve side effects when typed Apply with 2 argument list is passed in") {
assume(neverRuns3(sys.error("Sad times 3"))(0), "this is a clue")
}
it("should do nothing when is used to check s1 startsWith \"hi\"") {
assume(s1 startsWith "hi", "this is a clue")
assume(s1.startsWith("hi"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s2 startsWith \"hi\"") {
val e1 = intercept[TestCanceledException] {
assume(s2 startsWith "hi", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(s2 startsWith "hi", "this is a clue")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s2.startsWith("hi"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(s2.startsWith("hi"), "this is a clue")
| | | |
| | false "hi"
| "ScalaTest hi"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci1 startsWith 1") {
assume(ci1 startsWith 1, "this is a clue")
assume(ci1.startsWith(1), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci2 startsWith 1") {
val e1 = intercept[TestCanceledException] {
assume(ci2 startsWith 1, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(ci2 startsWith 1, "this is a clue")
| | | |
| 321 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci2.startsWith(1), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(ci2.startsWith(1), "this is a clue")
| | | |
| 321 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s2.startsWith(\"hi\")") {
assume(!s2.startsWith("hi"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s1.startsWith(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s1.startsWith("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(!s1.startsWith("hi"), "this is a clue")
| || | |
| || true "hi"
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s2 endsWith \"hi\"") {
assume(s2 endsWith "hi", "this is a clue")
assume(s2.endsWith("hi"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1 endsWith \"hi\"") {
val e1 = intercept[TestCanceledException] {
assume(s1 endsWith "hi", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(s1 endsWith "hi", "this is a clue")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s1.endsWith("hi"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(s1.endsWith("hi"), "this is a clue")
| | | |
| | false "hi"
| "hi ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 endsWith 1") {
assume(ci2 endsWith 1, "this is a clue")
assume(ci2.endsWith(1), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 endsWith 1") {
val e1 = intercept[TestCanceledException] {
assume(ci1 endsWith 1, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(ci1 endsWith 1, "this is a clue")
| | | |
| 123 false 1
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci1.endsWith(1), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(ci1.endsWith(1), "this is a clue")
| | | |
| 123 false 1
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.endsWith(\"hi\")") {
assume(!s1.endsWith("hi"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s2.endsWith(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s2.endsWith("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(!s2.endsWith("hi"), "this is a clue")
| || | |
| || true "hi"
| |"ScalaTest hi"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s3 contains \"hi\"") {
assume(s3 contains "hi", "this is a clue")
assume(s3.contains("hi"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s3 contains \"hello\"") {
val e1 = intercept[TestCanceledException] {
assume(s3 contains "hello", "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(s3 contains "hello", "this is a clue")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(s3.contains("hello"), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(s3.contains("hello"), "this is a clue")
| | | |
| | false "hello"
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check ci2 contains 2") {
assume(ci2 contains 2, "this is a clue")
assume(ci2.contains(2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(ci1 contains 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(ci1 contains 5, "this is a clue")
| | | |
| 123 false 5
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 13))
val e2 = intercept[TestCanceledException] {
assume(ci1.contains(5), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(ci1.contains(5), "this is a clue")
| | | |
| 123 false 5
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when is used to check !s1.contains(\"hello\")") {
assume(!s3.contains("hello"), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s3.contains(\"hi\")") {
val e1 = intercept[TestCanceledException] {
assume(!s3.contains("hi"), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(!s3.contains("hi"), "this is a clue")
| || | |
| || true "hi"
| |"Say hi to ScalaTest"
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1 contains 2") {
assume(l1 contains 2, "this is a clue")
assume(l1.contains(2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(l1 contains 5, "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(l1 contains 5, "this is a clue")
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(l1.contains(5), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(l1.contains(5), "this is a clue")
| | | |
| | false 5
| List(1, 2, 3)
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(l1 contains 5)") {
assume(!(l1 contains 5), "this is a clue")
assume(!l1.contains(5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1 contains 2)") {
val e1 = intercept[TestCanceledException] {
assume(!(l1 contains 2), "this is a clue")
}
e1.message should be (
Some(
"""this is a clue
|
|assume(!(l1 contains 2), "this is a clue")
| | | | |
| | | true 2
| | List(1, 2, 3)
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestCanceledException] {
assume(!l1.contains(2), "this is a clue")
}
e2.message should be (
Some(
"""this is a clue
|
|assume(!l1.contains(2), "this is a clue")
| || | |
| || true 2
| |List(1, 2, 3)
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check m1 contains 2") {
assume(m1 contains 2, "this is a clue")
assume(m1.contains(2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check m1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(m1 contains 5, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(m1 contains 5, "this is a clue")
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(m1.contains(5), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assume(m1.contains(5), "this is a clue")
| | | |
| | false 5
| $m1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !(m1 contains 5)") {
assume(!(m1 contains 5), "this is a clue")
assume(!m1.contains(5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(m1 contains 2)") {
val e1 = intercept[TestCanceledException] {
assume(!(m1 contains 2), "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(!(m1 contains 2), "this is a clue")
| | | | |
| | | true 2
| | $m1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
val e2 = intercept[TestCanceledException] {
assume(!m1.contains(2), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assume(!m1.contains(2), "this is a clue")
| || | |
| || true 2
| |$m1Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ct1 contains 8") {
assume(ct1 contains 8, "this is a clue")
assume(ct1.contains(8), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ct1 contains 5") {
val e1 = intercept[TestCanceledException] {
assume(ct1 contains 5, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(ct1 contains 5, "this is a clue")
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ct1.contains(5), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assume(ct1.contains(5), "this is a clue")
| | | |
| | false 5
| $ct1Str
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ct1.contains(5)") {
assume(!ct1.contains(5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ct1.contains(8)") {
val e1 = intercept[TestCanceledException] {
assume(!ct1.contains(8), "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(!ct1.contains(8), "this is a clue")
| || | |
| || true 8
| |$ct1Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 eq ci3") {
assume(ci1 eq ci3, "this is a clue")
assume(ci1.eq(ci3), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 eq ci2") {
val e1 = intercept[TestCanceledException] {
assume(ci1 eq ci2, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(ci1 eq ci2, "this is a clue")
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ci1.eq(ci2), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assume(ci1.eq(ci2), "this is a clue")
| | | |
| $ci1Str | $ci2Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.eq(ci2)") {
assume(!ci1.eq(ci2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ci1.eq(ci3)") {
val e = intercept[TestCanceledException] {
assume(!ci1.eq(ci3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!ci1.eq(ci3), "this is a clue")
| || | |
| |$ci1Str | $ci3Str
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check ci1 ne ci2") {
assume(ci1 ne ci2, "this is a clue")
assume(ci1.ne(ci2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check ci1 ne ci3") {
val e1 = intercept[TestCanceledException] {
assume(ci1 ne ci3, "this is a clue")
}
e1.message should be (
Some(
s"""this is a clue
|
|assume(ci1 ne ci3, "this is a clue")
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e1.failedCodeFileName should be (Some(fileName))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 14))
val e2 = intercept[TestCanceledException] {
assume(ci1.ne(ci3), "this is a clue")
}
e2.message should be (
Some(
s"""this is a clue
|
|assume(ci1.ne(ci3), "this is a clue")
| | | |
| $ci1Str | $ci3Str
| false
|""".stripMargin
)
)
e2.failedCodeFileName should be (Some(fileName))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !ci1.ne(ci3)") {
assume(!ci1.ne(ci3), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !ci1.ne(ci2)") {
val e = intercept[TestCanceledException] {
assume(!ci1.ne(ci2), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!ci1.ne(ci2), "this is a clue")
| || | |
| |123 | 321
| | true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s4.isEmpty") {
assume(s4.isEmpty, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s3.isEmpty") {
val e = intercept[TestCanceledException] {
assume(s3.isEmpty, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(s3.isEmpty, "this is a clue")
| | |
| | false
| "Say hi to ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !s3.isEmpty") {
assume(!s3.isEmpty, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s4.isEmpty") {
val e = intercept[TestCanceledException] {
assume(!s4.isEmpty, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!s4.isEmpty, "this is a clue")
| || |
| |"" true
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l2.isEmpty") {
assume(l2.isEmpty, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isEmpty") {
val e = intercept[TestCanceledException] {
assume(l1.isEmpty, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.isEmpty, "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isEmpty") {
assume(!l1.isEmpty, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l2.isEmpty") {
val e = intercept[TestCanceledException] {
assume(!l2.isEmpty, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!l2.isEmpty, "this is a clue")
| || |
| || true
| |$l2
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.isInstanceOf[String]") {
assume(s1.isInstanceOf[String], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isInstanceOf[String]") {
val e = intercept[TestCanceledException] {
assume(l1.isInstanceOf[String], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.isInstanceOf[String], "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check l1.isInstanceOf[List[Int]]") {
assume(l1.isInstanceOf[List[Int]], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.isInstanceOf[List[Int]]") {
val e = intercept[TestCanceledException] {
assume(s1.isInstanceOf[List[Int]], "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(s1.isInstanceOf[List[Int]], "this is a clue")
| | |
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check date.isInstanceOf[Date]") {
assume(date.isInstanceOf[Date], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.isInstanceOf[Date]") {
val e = intercept[TestCanceledException] {
assume(l1.isInstanceOf[Date], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.isInstanceOf[Date], "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.isInstanceOf[String]") {
assume(!l1.isInstanceOf[String], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !s1.isInstanceOf[String]") {
val e = intercept[TestCanceledException] {
assume(!s1.isInstanceOf[String], "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!s1.isInstanceOf[String], "this is a clue")
| || |
| || true
| |"hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !s1.isInstanceOf[List[Int]]") {
assume(!s1.isInstanceOf[List[Int]], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l1.isInstanceOf[List[Int]]") {
val e = intercept[TestCanceledException] {
assume(!l1.isInstanceOf[List[Int]], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!l1.isInstanceOf[List[Int]], "this is a clue")
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !l1.isInstanceOf[Date]") {
assume(!l1.isInstanceOf[Date], "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !date.isInstanceOf[Date]") {
val e = intercept[TestCanceledException] {
assume(!date.isInstanceOf[Date], "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!date.isInstanceOf[Date], "this is a clue")
| || |
| || true
| |$date
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check s1.length == 9") {
assume(s1.length == 12, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.length == 10") {
val e = intercept[TestCanceledException] {
assume(s1.length == 10, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(s1.length == 10, "this is a clue")
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.length == 3") {
assume(l1.length == 3, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.length == 10") {
val e = intercept[TestCanceledException] {
assume(l1.length == 10, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.length == 10, "this is a clue")
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.length == 10)") {
assume(!(s1.length == 10), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(s1.length == 9)") {
val e = intercept[TestCanceledException] {
assume(!(s1.length == 12), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!(s1.length == 12), "this is a clue")
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.length == 2)") {
assume(!(l1.length == 2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1.length == 9)") {
val e = intercept[TestCanceledException] {
assume(!(l1.length == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!(l1.length == 3), "this is a clue")
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check s1.size == 9") {
assume(s1.size == 12, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check s1.size == 10") {
val e = intercept[TestCanceledException] {
assume(s1.size == 10, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(s1.size == 10, "this is a clue")
| | | | |
| | 12 | 10
| | false
| "hi ScalaTest"
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check l1.size == 3") {
assume(l1.size == 3, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.size == 10") {
val e = intercept[TestCanceledException] {
assume(l1.size == 10, "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.size == 10, "this is a clue")
| | | | |
| | 3 | 10
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should do nothing when is used to check !(s1.size == 10)") {
assume(!(s1.size == 10), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(s1.size == 9)") {
val e = intercept[TestCanceledException] {
assume(!(s1.size == 12), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(!(s1.size == 12), "this is a clue")
| | | | | |
| | | 12 | 12
| | | true
| | "hi ScalaTest"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check !(l1.size == 2)") {
assume(!(l1.size == 2), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !(l1.size == 9) ") {
val e = intercept[TestCanceledException] {
assume(!(l1.size == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!(l1.size == 3), "this is a clue")
| | | | | |
| | | 3 | 3
| | | true
| | $l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should do nothing when is used to check l1.exists(_ == 3)") {
assume(l1.exists(_ == 3), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.exists(_ == 5) ") {
val e = intercept[TestCanceledException] {
assume(l1.exists(_ == 5), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.exists(_ == 5), "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when is used to check !l1.exists(_ == 5)") {
assume(!l1.exists(_ == 5), "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check !l1.exists(_ == 3)") {
val e = intercept[TestCanceledException] {
assume(!l1.exists(_ == 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(!l1.exists(_ == 3), "this is a clue")
| || |
| || true
| |$l1
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 15))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l1.exists(_ > 3)") {
val e = intercept[TestCanceledException] {
assume(l1.exists(_ > 3), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l1.exists(_ > 3), "this is a clue")
| | |
| | false
| $l1
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l3.exists(_.isEmpty)") {
val e = intercept[TestCanceledException] {
assume(l3.exists(_.isEmpty), "this is a clue")
}
e.message should be (
Some(
s"""this is a clue
|
|assume(l3.exists(_.isEmpty), "this is a clue")
| | |
| | false
| $l3Str
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should throw TestCanceledException with correct message and stack depth when is used to check l3.exists(false)") {
val e = intercept[TestCanceledException] {
assume(ci1.exists(321), "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(ci1.exists(321), "this is a clue")
| | | |
| 123 false 321
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 13))
}
it("should do nothing when used to check woof { meow(y = 5) } == \"woof\"") {
assume(woof { meow(y = 5) } == "woof", "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check woof { meow(y = 5) } == \"meow\"") {
val e = intercept[TestCanceledException] {
assume(woof { meow(y = 5) } == "meow", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(woof { meow(y = 5) } == "meow", "this is a clue")
| | | |
| "woof" | "meow"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
it("should do nothing when used to check multiline assert((b == a + 2) && (b - 2 <= a)) ") {
assume((b == a + 2) && (b - 2 <=
a), "this is a clue")
}
it("should throw friend message when used to check multiline assert((b == a + 2) && (b - 1 <= a))") {
val e = intercept[TestCanceledException] {
assume((b == a + 2) && (b - 1 <=
a), "this is a clue")
}
e.message shouldBe Some("5 equaled 5, but 4 was not less than or equal to 3 this is a clue")
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
}
it("should do nothing when a block of code that evaluates to true is passed in") {
assume({
val a = 1
val b = 2
val c = a + b
a < b || c == a + b
}, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when a block of code that evaluates to false is passed") {
val e = intercept[TestCanceledException] {
assume({ val a = 1; val b = 2; val c = a + b; a > b || c == b * b }, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume({ val a = 1; val b = 2; val c = a + b; a > b || c == b * b }, "this is a clue")
| | | | | | | | | |
| 1 | 2 | 3 | 2 4 2
| | | false
| | false
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 16))
}
it("should fallback to BooleanMacro when a block of code > 1 line is passed in ") {
val e = intercept[TestCanceledException] {
assume({
val a = 1
val b = 2
val c = a + b
a > b || c == b * b }, "this is a clue")
}
e.message should be (
Some(
"""{
| val a: Int = 1;
| val b: Int = 2;
| val c: Int = a.+(b);
| a.>(b).||(c.==(b.*(b)))
|} was false this is a clue""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 17))
}
it("should do nothing when used to check <person>Dude</person> == <person>Dude</person>") {
assume(<person>Dude</person> == <person>Dude</person>, "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check <person>Dude</person> == <person>Mary</person>") {
val e = intercept[TestCanceledException] {
assume(<person>Dude</person> == <person>Mary</person>, "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(<person>Dude</person> == <person>Mary</person>, "this is a clue")
| | | |
| | | <person>Mary</person>
| | false
| <person>Dude</person>
|""".stripMargin
)
)
}
it("should compile when used with org == xxx that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "test"
|assume(org == "test", "this is a clue")
""".stripMargin)
}
it("should compile when used with org === xxx that shadow org.scalactic") {
assertCompiles(
"""
|val org = "test"
|assume(org === "test", "this is a clue")
""".stripMargin)
}
it("should compile when used with org === xxx with TypeCheckedTripleEquals that shadow org.scalactic") {
assertCompiles(
"""
|class TestSpec extends FunSpec with org.scalactic.TypeCheckedTripleEquals {
| it("testing here") {
| val org = "test"
| assume(org === "test", "this is a clue")
| }
|}
""".stripMargin)
}
it("should compile when used with org.aCustomMethod that shadow org.scalactic") {
assertCompiles(
"""
|class Test {
| def aCustomMethod: Boolean = true
|}
|val org = new Test
|assume(org.aCustomMethod, "this is a clue")
""".stripMargin)
}
it("should compile when used with !org that shadow org.scalactic") {
assertCompiles(
"""
|val org = false
|assume(!org, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.isEmpty that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.isEmpty, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.isInstanceOf that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.isInstanceOf[String], "this is a clue")
""".stripMargin)
}
it("should compile when used with org.size == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = Array.empty[String]
|assume(org.size == 0, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.length == 0 that shadow org.scalactic") {
assertCompiles(
"""
|val org = ""
|assume(org.length == 0, "this is a clue")
""".stripMargin)
}
it("should compile when used with org.exists(_ == 'b') that shadow org.scalactic ") {
assertCompiles(
"""
|val org = "abc"
|assume(org.exists(_ == 'b'), "this is a clue")
""".stripMargin)
}
it("should do nothing when is used to check new String(\"test\") != \"test\"") {
assume(new String("test") == "test", "this is a clue")
}
it("should throw TestCanceledException with correct message and stack depth when is used to check new String(\"test\") != \"testing\"") {
val e = intercept[TestCanceledException] {
assume(new String("test") == "testing", "this is a clue")
}
e.message should be (
Some(
"""this is a clue
|
|assume(new String("test") == "testing", "this is a clue")
| | | |
| "test" | "testing"
| false
|""".stripMargin
)
)
e.failedCodeFileName should be (Some(fileName))
e.failedCodeLineNumber should be (Some(thisLineNumber - 14))
}
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/prop/NonGeneratedTableDrivenPropertyChecksSpec.scala | package org.scalatest
package prop
import java.lang.annotation.AnnotationFormatError
import java.nio.charset.CoderMalfunctionError
import javax.xml.parsers.FactoryConfigurationError
import javax.xml.transform.TransformerFactoryConfigurationError
import org.scalatest.FailureMessages._
import org.scalatest.SharedHelpers._
import org.scalatest._
import org.scalatest.exceptions.TestCanceledException
import org.scalatest.exceptions.DiscardedEvaluationException
/**
* Separate non-generated tests, for completeness
*/
class NonGeneratedTableDrivenPropertyChecksSpec extends Spec with Matchers with TableDrivenPropertyChecks with OptionValues {
object `forEvery/1 ` {
def colFun[A](s: Set[A]): TableFor1[A] = {
val table = Table(("column1"), s.toSeq: _*)
table
}
def `should pass when all elements passed` {
val col = colFun(Set(1, 2, 3))
forEvery(col) { e => e should be < 4}
}
def `should throw TestFailedException with correct stack depth and message when at least one element failed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
forEvery(col) { e => e should not equal 2}
}
e.failedCodeFileName should be(Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be(Some(thisLineNumber - 3))
val index = getIndex(col, 2)
e.message.value should be(s"forEvery failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 6})\n" +
s" Message: 2 equaled 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 8})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2 )"
)
}
def `should throw TestFailedException with correct stack depth and message when more than one element failed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
forEvery(col) { e => e should be < 2}
}
e.failedCodeFileName should be(Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be(Some(thisLineNumber - 3))
val itr = col.toIterator
val first = getNextNot[Int](itr, _ < 2)
val firstIndex = getIndex(col, first)
val second = getNextNot[Int](itr, _ < 2)
val secondIndex = getIndex(col, second)
e.message.value should be(s"forEvery failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 10})\n" +
s" Message: 2 was not less than 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 12})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 15})\n" +
s" Message: 3 was not less than 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 17})\n" +
s" Occurred at table row 2 (zero based, not counting headings), which had values (\n" +
s" column1 = 3 )"
)
}
def `should propagate TestPendingException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestPendingException] {
forEvery(col) { e => pending}
}
}
def `should propagate TestCanceledException thrown from assertion` {
val example = colFun(Set(1, 2, 3))
intercept[exceptions.TestCanceledException] {
forEvery(example) { e => cancel}
}
}
def `should not propagate DiscardedEvaluationException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
forEvery(col) { e => throw new DiscardedEvaluationException}
}
def `should propagate java.lang.annotation.AnnotationFormatError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[AnnotationFormatError] {
forEvery(col) { e => throw new AnnotationFormatError("test")}
}
}
def `should propagate java.nio.charset.CoderMalfunctionError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[CoderMalfunctionError] {
forEvery(col) { e => throw new CoderMalfunctionError(new RuntimeException("test"))}
}
}
def `should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[FactoryConfigurationError] {
forEvery(col) { e => throw new FactoryConfigurationError()}
}
}
def `should propagate java.lang.LinkageError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[LinkageError] {
forEvery(col) { e => throw new LinkageError()}
}
}
def `should propagate java.lang.ThreadDeath thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[ThreadDeath] {
forEvery(col) { e => throw new ThreadDeath()}
}
}
def `should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[TransformerFactoryConfigurationError] {
forEvery(col) { e => throw new TransformerFactoryConfigurationError()}
}
}
def `should propagate java.lang.VirtualMachineError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[VirtualMachineError] {
forEvery(col) { e => throw new VirtualMachineError() {}}
}
}
}
object `forEvery/2 ` {
def colFun[A](s: Set[A]): TableFor2[A, A] = {
val table = Table(("column1", "column2"), s.map(x => (x, x)).toSeq: _*)
table
}
def `should pass when all elements passed` {
val col = colFun(Set(1, 2, 3))
forEvery(col) { (e, _) => e should be < 4}
}
def `should throw TestFailedException with correct stack depth and message when at least one element failed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
forEvery(col) { (e, _) => e should not equal 2}
}
e.failedCodeFileName should be(Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be(Some(thisLineNumber - 3))
val index = getIndex(col, (2, 2))
e.message.value should be(s"forEvery failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 6})\n" +
s" Message: 2 equaled 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 8})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2\n" +
s" column2 = 2 )"
)
}
def `should throw TestFailedException with correct stack depth and message when more than one element failed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
forEvery(col) { (e, _) => e should be < 2}
}
e.failedCodeFileName should be(Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be(Some(thisLineNumber - 3))
val itr = col.toIterator
val first = getNextNot[(Int, Int)](itr, _._1 < 2)
val firstIndex = getIndex(col, first)
val second = getNextNot[(Int, Int)](itr, _._1 < 2)
val secondIndex = getIndex(col, second)
e.message.value should be(s"forEvery failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 10})\n" +
s" Message: 2 was not less than 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 12})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2\n" +
s" column2 = 2 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 16})\n" +
s" Message: 3 was not less than 2\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 18})\n" +
s" Occurred at table row 2 (zero based, not counting headings), which had values (\n" +
s" column1 = 3\n" +
s" column2 = 3 )"
)
}
def `should propagate not DiscardedEvaluationException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
forEvery(col) { (_, _) => throw new DiscardedEvaluationException}
}
def `should propagate TestPendingException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestPendingException] {
forEvery(col) { (e, _) => pending}
}
}
def `should propagate TestCanceledException thrown from assertion` {
val example = colFun(Set(1, 2, 3))
intercept[exceptions.TestCanceledException] {
forEvery(example) { (e, _) => cancel}
}
}
def `should propagate java.lang.annotation.AnnotationFormatError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[AnnotationFormatError] {
forEvery(col) { (e, _) => throw new AnnotationFormatError("test")}
}
}
def `should propagate java.nio.charset.CoderMalfunctionError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[CoderMalfunctionError] {
forEvery(col) { (e, _) => throw new CoderMalfunctionError(new RuntimeException("test"))}
}
}
def `should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[FactoryConfigurationError] {
forEvery(col) { (e, _) => throw new FactoryConfigurationError()}
}
}
def `should propagate java.lang.LinkageError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[LinkageError] {
forEvery(col) { (e, _) => throw new LinkageError()}
}
}
def `should propagate java.lang.ThreadDeath thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[ThreadDeath] {
forEvery(col) { (e, _) => throw new ThreadDeath()}
}
}
def `should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[TransformerFactoryConfigurationError] {
forEvery(col) { (e, _) => throw new TransformerFactoryConfigurationError()}
}
}
def `should propagate java.lang.VirtualMachineError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[VirtualMachineError] {
forEvery(col) { (e, _) => throw new VirtualMachineError() {}}
}
}
}
object `exists/1 ` {
def colFun[A](s: Set[A]): TableFor1[A] = {
val table = Table(("column1"), s.toSeq: _*)
table
}
def `should pass when one element passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { e => e should be (2) }
}
def `should pass when more than one element passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { e => e should be < 3 }
}
def `should evaluate all elements, and allow test to be canceled after one element passed` {
val col = colFun(Set(1, 2, 3))
intercept[TestCanceledException] {
exists(col) { e =>
if (e == 3) cancel("You got to three")
e should be < 3
}
}
}
def `should throw TestFailedException with correct stack depth and message when none of the elements passed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
exists(col) { e =>
e should be > 5
}
}
e.failedCodeFileName should be (Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
val itr = col.toIterator
val first = itr.next
val second = itr.next
val third = itr.next; println("Message: " + e.message.value)
e.message.value should be(s"exists failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 11})\n" +
s" Message: 1 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 12})\n" +
s" Occurred at table row 0 (zero based, not counting headings), which had values (\n" +
s" column1 = 1 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 16})\n" +
s" Message: 2 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 17})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 21})\n" +
s" Message: 3 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 22})\n" +
s" Occurred at table row 2 (zero based, not counting headings), which had values (\n" +
s" column1 = 3 )"
)
e.getCause should not be (null)
}
def `should pass when all of the elements passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { e => e should be < 5 }
}
def `should fail in empty case when all of the elements failed` {
val col = colFun(Set[Int]())
val e = intercept[exceptions.TestFailedException] {
exists(col) { e => fail("<there are no elements>") }
}
}
def `should propagate not DiscardedEvaluationException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
exists(col) { _ => throw new DiscardedEvaluationException}
}
}
def `should propagate TestPendingException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestPendingException] {
exists(col) { e => pending }
}
}
def `should propagate TestCanceledException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestCanceledException] {
exists(col) { e => cancel }
}
}
def `should propagate java.lang.annotation.AnnotationFormatError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[AnnotationFormatError] {
exists(col) { e => throw new AnnotationFormatError("test") }
}
}
def `should propagate java.nio.charset.CoderMalfunctionError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[CoderMalfunctionError] {
exists(col) { e => throw new CoderMalfunctionError(new RuntimeException("test")) }
}
}
def `should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[FactoryConfigurationError] {
exists(col) { e => throw new FactoryConfigurationError() }
}
}
def `should propagate java.lang.LinkageError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[LinkageError] {
exists(col) { e => throw new LinkageError() }
}
}
def `should propagate java.lang.ThreadDeath thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[ThreadDeath] {
exists(col) { e => throw new ThreadDeath() }
}
}
def `should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[TransformerFactoryConfigurationError] {
exists(col) { e => throw new TransformerFactoryConfigurationError() }
}
}
def `should propagate java.lang.VirtualMachineError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[VirtualMachineError] {
exists(col) { e => throw new VirtualMachineError() {} }
}
}
}
object `exists/2 ` {
def colFun[A](s: Set[A]): TableFor2[A, A] = {
val table = Table(("column1", "column2"), s.map(x => (x, x)).toSeq: _*)
table
}
def `should pass when one element passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { (e, _) => e should be (2) }
}
def `should pass when more than one element passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { (e, _) => e should be < 3 }
}
def `should throw TestFailedException with correct stack depth and message when none of the elements passed` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
exists(col) { (e, _) =>
e should be > 5
}
}
e.failedCodeFileName should be (Some("NonGeneratedTableDrivenPropertyChecksSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 5))
val itr = col.toIterator
val first = itr.next
val second = itr.next
val third = itr.next; println("Message: " + e.message.value)
e.message.value should be(s"exists failed, because: \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 11})\n" +
s" Message: 1 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 12})\n" +
s" Occurred at table row 0 (zero based, not counting headings), which had values (\n" +
s" column1 = 1\n" +
s" column2 = 1 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 17})\n" +
s" Message: 2 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 18})\n" +
s" Occurred at table row 1 (zero based, not counting headings), which had values (\n" +
s" column1 = 2\n" +
s" column2 = 2 ), \n" +
s" org.scalatest.exceptions.TableDrivenPropertyCheckFailedException: TestFailedException was thrown during property evaluation. (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 23})\n" +
s" Message: 3 was not greater than 5\n" +
s" Location: (NonGeneratedTableDrivenPropertyChecksSpec.scala:${thisLineNumber - 24})\n" +
s" Occurred at table row 2 (zero based, not counting headings), which had values (\n" +
s" column1 = 3\n" +
s" column2 = 3 )"
)
e.getCause should not be (null)
}
def `should pass when all of the elements passed` {
val col = colFun(Set(1, 2, 3))
exists(col) { (e, _) => e should be < 5 }
}
def `should fail in empty case when all of the elements failed` {
val col = colFun(Set[Int]())
val e = intercept[exceptions.TestFailedException] {
exists(col) { (e, _) => fail("<there are no elements>") }
}
}
def `should propagate not DiscardedEvaluationException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
val e = intercept[exceptions.TestFailedException] {
exists(col) { (_, _) => throw new DiscardedEvaluationException}
}
}
def `should propagate TestPendingException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestPendingException] {
exists(col) { (_, _) => pending }
}
}
def `should propagate TestCanceledException thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[exceptions.TestCanceledException] {
exists(col) { (_, _) => cancel }
}
}
def `should propagate java.lang.annotation.AnnotationFormatError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[AnnotationFormatError] {
exists(col) { (_, _) => throw new AnnotationFormatError("test") }
}
}
def `should propagate java.nio.charset.CoderMalfunctionError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[CoderMalfunctionError] {
exists(col) { (_, _) => throw new CoderMalfunctionError(new RuntimeException("test")) }
}
}
def `should propagate javax.xml.parsers.FactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[FactoryConfigurationError] {
exists(col) { (_, _) => throw new FactoryConfigurationError() }
}
}
def `should propagate java.lang.LinkageError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[LinkageError] {
exists(col) { (_, _) => throw new LinkageError() }
}
}
def `should propagate java.lang.ThreadDeath thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[ThreadDeath] {
exists(col) { (_, _) => throw new ThreadDeath() }
}
}
def `should propagate javax.xml.transform.TransformerFactoryConfigurationError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[TransformerFactoryConfigurationError] {
exists(col) { (_, _) => throw new TransformerFactoryConfigurationError() }
}
}
def `should propagate java.lang.VirtualMachineError thrown from assertion` {
val col = colFun(Set(1, 2, 3))
intercept[VirtualMachineError] {
exists(col) { (_, _) => throw new VirtualMachineError() {} }
}
}
}
}
/*
describe("forEvery") {
it("passes with one passing") {
val example = Table(
("passes", "message"),
(true, "passes")
)
forEvery(example) { (shouldPass, message) =>
assert(shouldPass, message)
}
}
it("passes with multiple passing") {
val example = Table(
("passes", "message"),
(true, "passes"),
(true, "passes 2")
)
forEvery(example) { (shouldPass, message) =>
assert(shouldPass, message)
}
}
it("fails with one passing and some failing") {
pendingUntilFixed {
val example = Table(
("passes", "message"),
(true, "passes"),
(false, "failure 1"),
(false, "failure 2")
)
forEvery(example) { (shouldPass, message) =>
assert(shouldPass, message)
}
}
}
it("fails when no passing and one failing") {
pendingUntilFixed {
val example = Table(
("passes", "message"),
(false, "failure 1")
)
forEvery(example) { (shouldPass, message) =>
assert(shouldPass, message)
}
}
}
it("fails when no passing and some failing") {
pendingUntilFixed {
val example = Table(
("passes", "message"),
(false, "failure 1"),
(false, "failure 2"),
(false, "failure 3")
)
forEvery(example) { (shouldPass, message) =>
assert(shouldPass, message)
}
}
}
}
}
*/
/*
class InspectorExampleSpec extends Spec with Matchers with Inspectors {
object `Inspector examples ` {
val list = Seq(1, 2, 3)
def `failing list for forAll` = {
forAll(list) { x =>
x should be < (2)
}
}
def `failing list for forEvery` = {
forEvery(list) { x =>
x should be < (2)
}
}
}
}
class NonGeneratedTableDrivenPropertyChecksSpec extends Spec with Matchers with NonGeneratedTableDrivenPropertyChecks {
object `examples for failing ` {
def `failing table for 1 forAll` {
val examples = Table(("a"),
(1))
forAll(examples) { a =>
a should be (2)
}
}
def `failing table for 2 forAll` {
val examples = Table(("a", "b"),
(1, 2))
forAll(examples) { case (a, b) =>
assert(a === 42)
}
}
}
}
*/
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldBeDefinedAtForAllSpec.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 SharedHelpers.thisLineNumber
import Matchers._
import exceptions.TestFailedException
class ShouldBeDefinedAtForAllSpec extends Spec {
def wasDefinedAt(left: Any, right: Any): String =
left + " was defined at " + right
def wasNotDefinedAt(left: Any, right: Any): String =
left + " was not defined at " + right
def equaled(left: Any, right: Any): String =
left + " equaled " + right
def didNotEqual(left: Any, right: Any): String =
left + " did not equal " + right
def errorMessage(index: Int, message: String, lineNumber: Int, left: Any): String =
"'all' inspection failed, because: \n" +
" at index " + index + ", " + message + " (ShouldBeDefinedAtForAllSpec.scala:" + lineNumber + ") \n" +
"in " + left
object `PartialFunction ` {
val fraction = new PartialFunction[Int, Int] {
def apply(d: Int) = 42 / d
def isDefinedAt(d: Int) = d != 0
}
val fraction2 = new PartialFunction[Int, Int] {
def apply(d: Int) = 42 / d
def isDefinedAt(d: Int) = d != 0
}
val list = List(fraction)
object `all(xs) should be definedAt` {
def `should do nothing when PartialFunction is defined at the specified value` {
all(List(fraction)) should be definedAt (6)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is not defined at the specified value` {
val caught = intercept[TestFailedException] {
all(list) should be definedAt (0)
}
assert(caught.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-and expression passed` {
all(list) should (be definedAt (6) and be definedAt (8))
all(list) should (be definedAt (6) and (be definedAt (8)))
all(list) should (be (definedAt (6)) and be (definedAt (8)))
all(list) should (equal (fraction) and be definedAt (8))
all(list) should (equal (fraction) and (be definedAt (8)))
all(list) should ((equal (fraction)) and be (definedAt (8)))
all(list) should (be definedAt (6) and equal (fraction))
all(list) should (be definedAt (6) and (equal (fraction)))
all(list) should (be (definedAt (6)) and (equal (fraction)))
}
def `should throw TestFailedException with correct stack depth when first expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (be definedAt (0) and be definedAt (8))
}
assert(caught1.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (be definedAt (0) and (be definedAt (8)))
}
assert(caught2.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (be (definedAt (0)) and be (definedAt (8)))
}
assert(caught3.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (equal (fraction2) and be definedAt (8))
}
assert(caught4.message === Some(errorMessage(0, didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (equal (fraction2) and (be definedAt (8)))
}
assert(caught5.message === Some(errorMessage(0, didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
all(list) should ((equal (fraction2)) and be (definedAt (8)))
}
assert(caught6.message === Some(errorMessage(0, didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught6.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when second expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (be definedAt (8) and be definedAt (0))
}
assert(caught1.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (be definedAt (8) and (be definedAt (0)))
}
assert(caught2.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (be (definedAt (8)) and be (definedAt (0)))
}
assert(caught3.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (be definedAt (8) and equal (fraction2))
}
assert(caught4.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (be definedAt (8) and (equal (fraction2)))
}
assert(caught5.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
all(list) should (be (definedAt (8)) and (equal (fraction2)))
}
assert(caught6.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", but " + didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught6.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (be definedAt (0) and be definedAt (0))
}
assert(caught1.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (be definedAt (0) and (be definedAt (0)))
}
assert(caught2.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (be (definedAt (0)) and be (definedAt (0)))
}
assert(caught3.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-or expression passed` {
all(list) should (be definedAt (6) or be definedAt (8))
all(list) should (be definedAt (6) or (be definedAt (8)))
all(list) should (be (definedAt (6)) or be (definedAt (8)))
all(list) should (equal (fraction) or be definedAt (8))
all(list) should (equal (fraction) or (be definedAt (8)))
all(list) should ((equal (fraction)) or be (definedAt (8)))
all(list) should (be definedAt (6) or equal (fraction))
all(list) should (be definedAt (6) or (equal (fraction)))
all(list) should (be (definedAt (6)) or (equal (fraction)))
}
def `should do nothing when first expression in logical-or expression failed` {
all(list) should (be definedAt (0) or be definedAt (8))
all(list) should (be definedAt (0) or (be definedAt (8)))
all(list) should (be (definedAt (0)) or be (definedAt (8)))
all(list) should (equal (fraction2) or be definedAt (8))
all(list) should (equal (fraction2) or (be definedAt (8)))
all(list) should ((equal (fraction2)) or be (definedAt (8)))
all(list) should (be definedAt (0) or equal (fraction))
all(list) should (be definedAt (0) or (equal (fraction)))
all(list) should (be (definedAt (0)) or (equal (fraction)))
}
def `should do nothing when second expressions in logical-or expression failed` {
all(list) should (be definedAt (6) or be definedAt (0))
all(list) should (be definedAt (6) or (be definedAt (0)))
all(list) should (be (definedAt (6)) or be (definedAt (0)))
all(list) should (equal (fraction) or be definedAt (0))
all(list) should (equal (fraction) or (be definedAt (0)))
all(list) should ((equal (fraction)) or be (definedAt (0)))
all(list) should (be definedAt (6) or equal (fraction2))
all(list) should (be definedAt (6) or (equal (fraction2)))
all(list) should (be (definedAt (6)) or (equal (fraction2)))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-or expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (be definedAt (0) or be definedAt (0))
}
assert(caught1.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", and " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (be definedAt (0) or (be definedAt (0)))
}
assert(caught2.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", and " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (be (definedAt (0)) or be (definedAt (0)))
}
assert(caught3.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", and " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (be definedAt (0) or equal (fraction2))
}
assert(caught4.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", and " + didNotEqual(fraction, fraction2), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (equal (fraction2) or (be definedAt (0)))
}
assert(caught5.message === Some(errorMessage(0, didNotEqual(fraction, fraction2) + ", and " + wasNotDefinedAt(fraction, 0), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `all(xs) should not be definedAt` {
def `should do nothing when PartialFunction is not defined at the specified value` {
all(list) should not be definedAt (0)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is defined at the specified value` {
val caught = intercept[TestFailedException] {
all(list) should not be definedAt (8)
}
assert(caught.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-and expression passed` {
all(list) should (not be definedAt (0) and not be definedAt (0))
all(list) should (not be definedAt (0) and (not be definedAt (0)))
all(list) should (not be (definedAt (0)) and not be (definedAt (0)))
all(list) should (not equal (fraction2) and not be definedAt (0))
all(list) should (not equal (fraction2) and (not be definedAt (0)))
all(list) should ((not equal (fraction2)) and not be (definedAt (0)))
all(list) should (not be definedAt (0) and not equal (fraction2))
all(list) should (not be definedAt (0) and (not equal (fraction2)))
all(list) should (not be (definedAt (0)) and (not equal (fraction2)))
}
def `should throw TestFailedException with correct stack depth when first expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) and not be definedAt (0))
}
assert(caught1.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) and (not be definedAt (0)))
}
assert(caught2.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (not be (definedAt (8)) and not be (definedAt (0)))
}
assert(caught3.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (not equal (fraction) and not be definedAt (0))
}
assert(caught4.message === Some(errorMessage(0, equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (not equal (fraction) and (not be definedAt (8)))
}
assert(caught5.message === Some(errorMessage(0, equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
all(list) should ((not equal (fraction)) and not be (definedAt (8)))
}
assert(caught6.message === Some(errorMessage(0, equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught6.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when second expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (not be definedAt (0) and not be definedAt (8))
}
assert(caught1.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (not be definedAt (0) and (not be definedAt (8)))
}
assert(caught2.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (not be (definedAt (0)) and not be (definedAt (8)))
}
assert(caught3.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (not be definedAt (0) and not equal (fraction))
}
assert(caught4.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (not be definedAt (0) and (not equal (fraction)))
}
assert(caught5.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught6 = intercept[TestFailedException] {
all(list) should (not be (definedAt (0)) and (not equal (fraction)))
}
assert(caught6.message === Some(errorMessage(0, wasNotDefinedAt(fraction, 0) + ", but " + equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught6.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught6.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-and expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) and not be definedAt (8))
}
assert(caught1.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) and (not be definedAt (8)))
}
assert(caught2.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (not be (definedAt (8)) and not be (definedAt (8)))
}
assert(caught3.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
}
def `should do nothing when both expressions in logical-or expression passed` {
all(list) should (not be definedAt (0) or not be definedAt (0))
all(list) should (not be definedAt (0) or (not be definedAt (0)))
all(list) should (not be (definedAt (0)) or not be (definedAt (0)))
all(list) should (not equal (fraction2) or not be definedAt (0))
all(list) should (not equal (fraction2) or (not be definedAt (0)))
all(list) should ((not equal (fraction2)) or not be (definedAt (0)))
all(list) should (not be definedAt (0) or not equal (fraction2))
all(list) should (not be definedAt (0) or (not equal (fraction2)))
all(list) should (not be (definedAt (0)) or (not equal (fraction2)))
}
def `should do nothing when first expression in logical-or expression failed` {
all(list) should (not be definedAt (8) or not be definedAt (0))
all(list) should (not be definedAt (8) or (not be definedAt (0)))
all(list) should (not be (definedAt (8)) or not be (definedAt (0)))
all(list) should (not equal (fraction) or not be definedAt (0))
all(list) should (not equal (fraction) or (not be definedAt (0)))
all(list) should ((not equal (fraction)) or not be (definedAt (0)))
all(list) should (not be definedAt (8) or not equal (fraction2))
all(list) should (not be definedAt (8) or (not equal (fraction2)))
all(list) should (not be (definedAt (8)) or (not equal (fraction2)))
}
def `should do nothing when second expressions in logical-or expression failed` {
all(list) should (not be definedAt (0) or not be definedAt (8))
all(list) should (not be definedAt (0) or (not be definedAt (8)))
all(list) should (not be (definedAt (0)) or not be (definedAt (8)))
all(list) should (not equal (fraction2) or not be definedAt (8))
all(list) should (not equal (fraction2) or (not be definedAt (8)))
all(list) should ((not equal (fraction2)) or not be (definedAt (8)))
all(list) should (not be definedAt (0) or not equal (fraction))
all(list) should (not be definedAt (0) or (not equal (fraction)))
all(list) should (not be (definedAt (0)) or (not equal (fraction)))
}
def `should throw TestFailedException with correct stack depth when both expression in logical-or expression failed` {
val caught1 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) or not be definedAt (8))
}
assert(caught1.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", and " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught1.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught1.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught2 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) or (not be definedAt (8)))
}
assert(caught2.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", and " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught2.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught2.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught3 = intercept[TestFailedException] {
all(list) should (not be (definedAt (8)) or not be (definedAt (8)))
}
assert(caught3.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", and " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught3.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught3.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught4 = intercept[TestFailedException] {
all(list) should (not be definedAt (8) or not equal (fraction))
}
assert(caught4.message === Some(errorMessage(0, wasDefinedAt(fraction, 8) + ", and " + equaled(fraction, fraction), thisLineNumber - 2, list)))
assert(caught4.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught4.failedCodeLineNumber === Some(thisLineNumber - 4))
val caught5 = intercept[TestFailedException] {
all(list) should (not equal (fraction) or (not be definedAt (8)))
}
assert(caught5.message === Some(errorMessage(0, equaled(fraction, fraction) + ", and " + wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught5.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught5.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
object `all(xs) shouldNot be definedAt` {
def `should do nothing when PartialFunction is not defined at the specified value` {
all(list) shouldNot be definedAt (0)
}
def `should throw TestFailedException with correct stack depth when PartialFunction is defined at the specified value` {
val caught = intercept[TestFailedException] {
all(list) shouldNot be definedAt (8)
}
assert(caught.message === Some(errorMessage(0, wasDefinedAt(fraction, 8), thisLineNumber - 2, list)))
assert(caught.failedCodeFileName === Some("ShouldBeDefinedAtForAllSpec.scala"))
assert(caught.failedCodeLineNumber === Some(thisLineNumber - 4))
}
}
}
}
|
cquiroz/scalatest | scalactic-macro/src/main/scala/org/scalactic/anyvals/DigitChar.scala | <filename>scalactic-macro/src/main/scala/org/scalactic/anyvals/DigitChar.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.language.implicitConversions
private[scalactic] final class DigitChar private (val value: Char) extends AnyVal {
override def toString: String = s"DigitChar($value)"
def toByte: Byte = value.toByte
def toShort: Short = value.toShort
def toChar: Char = value.toChar
def toInt: Int = value.toInt
def toLong: Long = value.toLong
def toFloat: Float = value.toFloat
def toDouble: Double = value.toDouble
def max(that: DigitChar): DigitChar =
if (math.max(value.toInt, that.value.toInt) == value.toInt) this
else that
def min(that: DigitChar): DigitChar =
if (math.min(value.toInt, that.value.toInt) == value.toInt) this
else that
def asDigit: Int = Character.digit(value, Character.MAX_RADIX) // from RichChar
def asDigitPosInt: PosInt = PosInt.from(asDigit).get
def asDigitPosZInt: PosZInt = PosZInt.from(asDigit).get
/**
* Returns the bitwise negation of this value.
* @example {{{
* ~5 == -6
* // in binary: ~00000101 ==
* // 11111010
* }}}
*/
def unary_~ : Int = ~value.asDigit
/** Returns this value, unmodified. */
def unary_+ : DigitChar = this
/** Returns the negation of this value. */
def unary_- : Int = -value
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): Int = 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): Int = 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): Int = 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): Int = 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): Int = 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): Int = 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): Int = value | x
/**
* Returns the bitwise OR of this value and `x`.
* @example {{{
* (0xf0 | 0xaa) == 0xfa
* // in binary: 11110000
* // | 10101010
* // --------
* // 11111010
* }}}
*/
def |(x: Short): Int = value | x
/**
* Returns the bitwise OR of this value and `x`.
* @example {{{
* (0xf0 | 0xaa) == 0xfa
* // in binary: 11110000
* // | 10101010
* // --------
* // 11111010
* }}}
*/
def |(x: Char): Int = value | x
/**
* Returns the bitwise OR of this value and `x`.
* @example {{{
* (0xf0 | 0xaa) == 0xfa
* // in binary: 11110000
* // | 10101010
* // --------
* // 11111010
* }}}
*/
def |(x: Int): Int = 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): Int = value & x
/**
* Returns the bitwise AND of this value and `x`.
* @example {{{
* (0xf0 & 0xaa) == 0xa0
* // in binary: 11110000
* // & 10101010
* // --------
* // 10100000
* }}}
*/
def &(x: Short): Int = value & x
/**
* Returns the bitwise AND of this value and `x`.
* @example {{{
* (0xf0 & 0xaa) == 0xa0
* // in binary: 11110000
* // & 10101010
* // --------
* // 10100000
* }}}
*/
def &(x: Char): Int = value & x
/**
* Returns the bitwise AND of this value and `x`.
* @example {{{
* (0xf0 & 0xaa) == 0xa0
* // in binary: 11110000
* // & 10101010
* // --------
* // 10100000
* }}}
*/
def &(x: Int): Int = 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): Int = value ^ x
/**
* Returns the bitwise XOR of this value and `x`.
* @example {{{
* (0xf0 ^ 0xaa) == 0x5a
* // in binary: 11110000
* // ^ 10101010
* // --------
* // 01011010
* }}}
*/
def ^(x: Short): Int = value ^ x
/**
* Returns the bitwise XOR of this value and `x`.
* @example {{{
* (0xf0 ^ 0xaa) == 0x5a
* // in binary: 11110000
* // ^ 10101010
* // --------
* // 01011010
* }}}
*/
def ^(x: Char): Int = value ^ x
/**
* Returns the bitwise XOR of this value and `x`.
* @example {{{
* (0xf0 ^ 0xaa) == 0x5a
* // in binary: 11110000
* // ^ 10101010
* // --------
* // 01011010
* }}}
*/
def ^(x: Int): Int = 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): Int = value + x
/** Returns the sum of this value and `x`. */
def +(x: Short): Int = value + x
/** Returns the sum of this value and `x`. */
def +(x: Char): Int = value + x
/** Returns the sum of this value and `x`. */
def +(x: Int): Int = 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): Int = value - x
/** Returns the difference of this value and `x`. */
def -(x: Short): Int = value - x
/** Returns the difference of this value and `x`. */
def -(x: Char): Int = value - x
/** Returns the difference of this value and `x`. */
def -(x: Int): Int = 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): Int = value * x
/** Returns the product of this value and `x`. */
def *(x: Short): Int = value * x
/** Returns the product of this value and `x`. */
def *(x: Char): Int = value * x
/** Returns the product of this value and `x`. */
def *(x: Int): Int = 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): Int = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Short): Int = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Char): Int = value / x
/** Returns the quotient of this value and `x`. */
def /(x: Int): Int = 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): Int = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Short): Int = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Char): Int = value % x
/** Returns the remainder of the division of this value by `x`. */
def %(x: Int): Int = 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
}
private[scalactic] object DigitChar {
def from(value: Char): Option[DigitChar] =
if (value >= MinValue && value <= MaxValue) Some(new DigitChar(value))
else None
import scala.language.experimental.macros
implicit def apply(value: Char): DigitChar = macro DigitCharMacro.apply
/** The smallest value representable as a DigitChar. */
final val MinValue = '0'
/** The largest value representable as a DigitChar. */
final val MaxValue = '9'
/** Language mandated coercions from Char to "wider" types. */
implicit def digitChar2Int(x: DigitChar): Int = x.toInt
implicit def digitChar2Long(x: DigitChar): Long = x.toLong
implicit def digitChar2Float(x: DigitChar): Float = x.toFloat
implicit def digitChar2Double(x: DigitChar): Double = x.toDouble
implicit def digitChar2PosInt(x: DigitChar): PosInt = PosInt.from(x.toInt).get
implicit def digitChar2PosLong(x: DigitChar): PosLong = PosLong.from(x.toLong).get
implicit def digitChar2PosFloat(x: DigitChar): PosFloat = PosFloat.from(x.toFloat).get
implicit def digitChar2PosDouble(x: DigitChar): PosDouble = PosDouble.from(x.toDouble).get
implicit def digitChar2PosZInt(x: DigitChar): PosZInt = PosZInt.from(x.toInt).get
implicit def digitChar2PosZLong(x: DigitChar): PosZLong = PosZLong.from(x.toLong).get
implicit def digitChar2PosZFloat(x: DigitChar): PosZFloat = PosZFloat.from(x.toFloat).get
implicit def digitChar2PosZDouble(x: DigitChar): PosZDouble = PosZDouble.from(x.toDouble).get
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/tools/MemoryReporter.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.Reporter
import org.scalatest.events.TestFailed
import org.scalatest.events.TestCanceled
import org.scalatest.events.RunCompleted
import org.scalatest.events.SuiteAborted
import org.scalatest.events.Event
import scala.collection.mutable
/**
* A <code>Reporter</code> that writes a file listing any tests that
* failed or canceled during a run, so they can be rerun if desired.
*/
private[scalatest] class MemoryReporter(outputFile: String)
extends Reporter
{
private val mementos = mutable.Set.empty[Memento]
//
// Records TestFailed, TestCanceled, and SuiteAborted events.
// Generates output file listing the events upon receipt of a
// RunCompleted event, to enable rerunning of just those tests
// next time.
//
def apply(event: Event) {
event match {
case e: TestFailed => mementos += Memento(e)
case e: TestCanceled => mementos += Memento(e)
case e: SuiteAborted => mementos += Memento(e)
case _: RunCompleted => Memento.writeToFile(outputFile, mementos.toSet)
case _ =>
}
}
}
|
cquiroz/scalatest | scalatest.js/src/main/scala/org/scalatest/tools/SummaryCounter.scala | package org.scalatest.tools
import org.scalatest.events.ExceptionalEvent
import scala.collection.mutable.ListBuffer
private[tools] class SummaryCounter {
// scala.js is thread-safe
var testsSucceededCount, testsFailedCount, testsIgnoredCount, testsPendingCount, testsCanceledCount, suitesCompletedCount, suitesAbortedCount, scopesPendingCount = 0
val reminderEventsQueue = new ListBuffer[ExceptionalEvent]
def incrementTestsSucceededCount() {
testsSucceededCount = testsSucceededCount + 1
}
def incrementTestsFailedCount() {
testsFailedCount = testsFailedCount + 1
}
def incrementTestsIgnoredCount() {
testsIgnoredCount = testsIgnoredCount + 1
}
def incrementTestsPendingCount() {
testsPendingCount = testsPendingCount + 1
}
def incrementTestsCanceledCount() {
testsCanceledCount = testsCanceledCount + 1
}
def incrementSuitesCompletedCount() {
suitesCompletedCount = suitesCompletedCount + 1
}
def incrementSuitesAbortedCount() {
suitesAbortedCount = suitesAbortedCount + 1
}
def incrementScopesPendingCount() {
scopesPendingCount = scopesPendingCount + 1
}
def recordReminderEvents(events: ExceptionalEvent) {
reminderEventsQueue += events
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/SeveredStackTraces.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.exceptions.StackDepth
/**
* Trait that causes <a href="exceptions/StackDepth.html"><code>StackDepth</code></a> exceptions thrown by a running test (such as <a href="exceptions/TestFailedException.html"><code>TestFailedException</code></a>s) to have
* the exception's stack trace severed at the stack depth. Because the stack depth indicates the exact line of code that caused
* the exception to be thrown, the severed stack trace will show that offending line of code on top. This can make the line
* of test code that discovered a problem to be more easily found in IDEs and tools that don't make use of
* ScalaTest's <code>StackDepth</code> exceptions directly.
*
* @author <NAME>
*/
trait SeveredStackTraces extends SuiteMixin { this: Suite =>
/**
* Invokes <code>super.withFixture(test)</code> and transforms a thrown <code>StackDepth</code> exception by severing
* its stack trace at the stack depth.
*/
abstract override def withFixture(test: NoArgTest): Outcome = {
super.withFixture(test) match {
case Exceptional(e: StackDepth) => Exceptional(e.severedAtStackDepth)
case o => o
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ParallelTestExecutionSuiteTimeoutExamples.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.events.Event
import org.scalatest.prop.Tables
import org.scalatest.events.TestStarting
import org.scalatest.events.TestSucceeded
import scala.collection.mutable.ListBuffer
import org.scalatest.events.ScopeClosed
import org.scalatest.time.Span
import org.scalatest.time.Millis
trait SuiteTimeoutSetting { s: ParallelTestExecution =>
override abstract def sortingTimeout: Span = Span(300, Millis)
}
trait SuiteTimeoutSuites extends EventHelpers {
def suite1: Suite with SuiteTimeoutSetting
def suite2: Suite with SuiteTimeoutSetting
val holdingSuiteId: String
val holdingTestName: String
val holdingScopeClosedName: Option[String]
val holdUntilEventCount: Int
def assertSuiteTimeoutTest(events: List[Event])
}
class SuiteHoldingReporter(dispatch: Reporter, holdingSuiteId: String, holdingTestName: String, holdingScopeClosedName: Option[String]) extends CatchReporter {
val out = System.err
private val holdEvents = new ListBuffer[Event]()
override protected def doApply(event: Event) {
event match {
case testStarting: TestStarting if testStarting.suiteId == holdingSuiteId && testStarting.testName == holdingTestName =>
holdEvents += testStarting
case testSucceeded: TestSucceeded if testSucceeded.suiteId == holdingSuiteId && testSucceeded.testName == holdingTestName =>
holdEvents += testSucceeded
case scopeClosed: ScopeClosed if holdingScopeClosedName.isDefined && scopeClosed.message == holdingScopeClosedName.get =>
holdEvents += scopeClosed
case _ => dispatch(event)
}
}
protected def doDispose() {}
def fireHoldEvents() {
holdEvents.foreach(dispatch(_))
}
}
object ParallelTestExecutionSuiteTimeoutExamples extends Tables {
def suiteTimeoutExamples =
Table(
"pair",
new ExampleParallelTestExecutionSuiteTimeoutSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutFunSuitePair,
new ExampleParallelTestExecutionSuiteTimeoutFunSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutFeatureSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutFlatSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutFreeSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutPropSpecPair,
new ExampleParallelTestExecutionSuiteTimeoutWordSpecPair
)
}
class ExampleParallelTestExecutionSuiteTimeoutSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "test 3"
val holdingScopeClosedName = None
val holdUntilEventCount = 13
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(5), suite2.suiteId)
checkTestStarting(events(6), "test 1")
checkTestSucceeded(events(7), "test 1")
checkTestStarting(events(8), "test 2")
checkTestSucceeded(events(9), "test 2")
checkTestStarting(events(10), "test 3")
checkTestSucceeded(events(11), "test 3")
checkSuiteCompleted(events(12), suite2.suiteId)
checkTestStarting(events(13), "test 3")
checkTestSucceeded(events(14), "test 3")
checkSuiteCompleted(events(15), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutSpec extends Spec with ParallelTestExecution with SuiteTimeoutSetting {
def `test 1` {}
def `test 2` {}
def `test 3` {}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureSpec extends fixture.Spec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
def `test 1`(fixture: String) {}
def `test 2`(fixture: String) {}
def `test 3`(fixture: String) {}
}
class ExampleParallelTestExecutionSuiteTimeoutFunSuitePair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutFunSuite
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureFunSuite
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Test 3"
val holdingScopeClosedName = None
val holdUntilEventCount = 13
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(5), suite2.suiteId)
checkTestStarting(events(6), "Fixture Test 1")
checkTestSucceeded(events(7), "Fixture Test 1")
checkTestStarting(events(8), "Fixture Test 2")
checkTestSucceeded(events(9), "Fixture Test 2")
checkTestStarting(events(10), "Fixture Test 3")
checkTestSucceeded(events(11), "Fixture Test 3")
checkSuiteCompleted(events(12), suite2.suiteId)
checkTestStarting(events(13), "Test 3")
checkTestSucceeded(events(14), "Test 3")
checkSuiteCompleted(events(15), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFunSuite extends FunSuite with ParallelTestExecution with SuiteTimeoutSetting {
test("Test 1") {}
test("Test 2") {}
test("Test 3") {}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureFunSuite extends fixture.FunSuite with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
test("Fixture Test 1") { fixture => }
test("Fixture Test 2") { fixture => }
test("Fixture Test 3") { fixture => }
}
class ExampleParallelTestExecutionSuiteTimeoutFunSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutFunSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureFunSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Scope 2 Test 4"
val holdingScopeClosedName = Some("Scope 2")
val holdUntilEventCount = 24
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(10), suite2.suiteId)
checkScopeOpened(events(11), "Fixture Scope 1")
checkTestStarting(events(12), "Fixture Scope 1 Fixture Test 1")
checkTestSucceeded(events(13), "Fixture Scope 1 Fixture Test 1")
checkTestStarting(events(14), "Fixture Scope 1 Fixture Test 2")
checkTestSucceeded(events(15), "Fixture Scope 1 Fixture Test 2")
checkScopeClosed(events(16), "Fixture Scope 1")
checkScopeOpened(events(17), "Fixture Scope 2")
checkTestStarting(events(18), "Fixture Scope 2 Fixture Test 3")
checkTestSucceeded(events(19), "Fixture Scope 2 Fixture Test 3")
checkTestStarting(events(20), "Fixture Scope 2 Fixture Test 4")
checkTestSucceeded(events(21), "Fixture Scope 2 Fixture Test 4")
checkScopeClosed(events(22), "Fixture Scope 2")
checkSuiteCompleted(events(23), suite2.suiteId)
checkTestStarting(events(24), "Scope 2 Test 4")
checkTestSucceeded(events(25), "Scope 2 Test 4")
checkScopeClosed(events(26), "Scope 2")
checkSuiteCompleted(events(27), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFunSpec extends FunSpec with ParallelTestExecution with SuiteTimeoutSetting {
describe("Scope 1") {
it("Test 1") {}
it("Test 2") {}
}
describe("Scope 2") {
it("Test 3") {}
it("Test 4") {}
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureFunSpec extends fixture.FunSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
describe("Fixture Scope 1") {
it("Fixture Test 1") { fixture => }
it("Fixture Test 2") { fixture => }
}
describe("Fixture Scope 2") {
it("Fixture Test 3") { fixture => }
it("Fixture Test 4") { fixture => }
}
}
class ExampleParallelTestExecutionSuiteTimeoutFeatureSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutFeatureSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureFeatureSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Feature: Scope 2 Scenario: Test 4"
val holdingScopeClosedName = Some("Feature: Scope 2")
val holdUntilEventCount = 24
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(10), suite2.suiteId)
checkScopeOpened(events(11), "Feature: Fixture Scope 1")
checkTestStarting(events(12), "Feature: Fixture Scope 1 Scenario: Fixture Test 1")
checkTestSucceeded(events(13), "Feature: Fixture Scope 1 Scenario: Fixture Test 1")
checkTestStarting(events(14), "Feature: Fixture Scope 1 Scenario: Fixture Test 2")
checkTestSucceeded(events(15), "Feature: Fixture Scope 1 Scenario: Fixture Test 2")
checkScopeClosed(events(16), "Feature: Fixture Scope 1")
checkScopeOpened(events(17), "Feature: Fixture Scope 2")
checkTestStarting(events(18), "Feature: Fixture Scope 2 Scenario: Fixture Test 3")
checkTestSucceeded(events(19), "Feature: Fixture Scope 2 Scenario: Fixture Test 3")
checkTestStarting(events(20), "Feature: Fixture Scope 2 Scenario: Fixture Test 4")
checkTestSucceeded(events(21), "Feature: Fixture Scope 2 Scenario: Fixture Test 4")
checkScopeClosed(events(22), "Feature: Fixture Scope 2")
checkSuiteCompleted(events(23), suite2.suiteId)
checkTestStarting(events(24), "Feature: Scope 2 Scenario: Test 4")
checkTestSucceeded(events(25), "Feature: Scope 2 Scenario: Test 4")
checkScopeClosed(events(26), "Feature: Scope 2")
checkSuiteCompleted(events(27), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFeatureSpec extends FeatureSpec with ParallelTestExecution with SuiteTimeoutSetting {
feature("Scope 1") {
scenario("Test 1") {}
scenario("Test 2") {}
}
feature("Scope 2") {
scenario("Test 3") {}
scenario("Test 4") {}
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureFeatureSpec extends fixture.FeatureSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
feature("Fixture Scope 1") {
scenario("Fixture Test 1") { fixture => }
scenario("Fixture Test 2") { fixture =>}
}
feature("Fixture Scope 2") {
scenario("Fixture Test 3") { fixture => }
scenario("Fixture Test 4") { fixture => }
}
}
class ExampleParallelTestExecutionSuiteTimeoutFlatSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutFlatSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureFlatSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Scope 2 should Test 4"
val holdingScopeClosedName = Some("Scope 2")
val holdUntilEventCount = 24
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(10), suite2.suiteId)
checkScopeOpened(events(11), "Fixture Scope 1")
checkTestStarting(events(12), "Fixture Scope 1 should Fixture Test 1")
checkTestSucceeded(events(13), "Fixture Scope 1 should Fixture Test 1")
checkTestStarting(events(14), "Fixture Scope 1 should Fixture Test 2")
checkTestSucceeded(events(15), "Fixture Scope 1 should Fixture Test 2")
checkScopeClosed(events(16), "Fixture Scope 1")
checkScopeOpened(events(17), "Fixture Scope 2")
checkTestStarting(events(18), "Fixture Scope 2 should Fixture Test 3")
checkTestSucceeded(events(19), "Fixture Scope 2 should Fixture Test 3")
checkTestStarting(events(20), "Fixture Scope 2 should Fixture Test 4")
checkTestSucceeded(events(21), "Fixture Scope 2 should Fixture Test 4")
checkScopeClosed(events(22), "Fixture Scope 2")
checkSuiteCompleted(events(23), suite2.suiteId)
checkTestStarting(events(24), "Scope 2 should Test 4")
checkTestSucceeded(events(25), "Scope 2 should Test 4")
checkScopeClosed(events(26), "Scope 2")
checkSuiteCompleted(events(27), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFlatSpec extends FlatSpec with ParallelTestExecution with SuiteTimeoutSetting {
behavior of "Scope 1"
it should "Test 1" in {}
it should "Test 2" in {}
behavior of "Scope 2"
it should "Test 3" in {}
it should "Test 4" in {}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureFlatSpec extends fixture.FlatSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
behavior of "Fixture Scope 1"
it should "Fixture Test 1" in { fixture => }
it should "Fixture Test 2" in { fixture => }
behavior of "Fixture Scope 2"
it should "Fixture Test 3" in { fixture => }
it should "Fixture Test 4" in { fixture => }
}
class ExampleParallelTestExecutionSuiteTimeoutFreeSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutFreeSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureFreeSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Scope 2 Test 4"
val holdingScopeClosedName = Some("Scope 2")
val holdUntilEventCount = 24
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(10), suite2.suiteId)
checkScopeOpened(events(11), "Fixture Scope 1")
checkTestStarting(events(12), "Fixture Scope 1 Fixture Test 1")
checkTestSucceeded(events(13), "Fixture Scope 1 Fixture Test 1")
checkTestStarting(events(14), "Fixture Scope 1 Fixture Test 2")
checkTestSucceeded(events(15), "Fixture Scope 1 Fixture Test 2")
checkScopeClosed(events(16), "Fixture Scope 1")
checkScopeOpened(events(17), "Fixture Scope 2")
checkTestStarting(events(18), "Fixture Scope 2 Fixture Test 3")
checkTestSucceeded(events(19), "Fixture Scope 2 Fixture Test 3")
checkTestStarting(events(20), "Fixture Scope 2 Fixture Test 4")
checkTestSucceeded(events(21), "Fixture Scope 2 Fixture Test 4")
checkScopeClosed(events(22), "Fixture Scope 2")
checkSuiteCompleted(events(23), suite2.suiteId)
checkTestStarting(events(24), "Scope 2 Test 4")
checkTestSucceeded(events(25), "Scope 2 Test 4")
checkScopeClosed(events(26), "Scope 2")
checkSuiteCompleted(events(27), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFreeSpec extends FreeSpec with ParallelTestExecution with SuiteTimeoutSetting {
"Scope 1" - {
"Test 1" in {}
"Test 2" in {}
}
"Scope 2" - {
"Test 3" in {}
"Test 4" in {}
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureFreeSpec extends fixture.FreeSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
"Fixture Scope 1" - {
"Fixture Test 1" in { fixture => }
"Fixture Test 2" in { fixture => }
}
"Fixture Scope 2" - {
"Fixture Test 3" in { fixture => }
"Fixture Test 4" in { fixture => }
}
}
class ExampleParallelTestExecutionSuiteTimeoutPropSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutPropSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixturePropSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Test 3"
val holdingScopeClosedName = None
val holdUntilEventCount = 13
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(5), suite2.suiteId)
checkTestStarting(events(6), "Fixture Test 1")
checkTestSucceeded(events(7), "Fixture Test 1")
checkTestStarting(events(8), "Fixture Test 2")
checkTestSucceeded(events(9), "Fixture Test 2")
checkTestStarting(events(10), "Fixture Test 3")
checkTestSucceeded(events(11), "Fixture Test 3")
checkSuiteCompleted(events(12), suite2.suiteId)
checkTestStarting(events(13), "Test 3")
checkTestSucceeded(events(14), "Test 3")
checkSuiteCompleted(events(15), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutPropSpec extends PropSpec with ParallelTestExecution with SuiteTimeoutSetting {
property("Test 1") {}
property("Test 2") {}
property("Test 3") {}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixturePropSpec extends fixture.PropSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
property("Fixture Test 1") { fixture => }
property("Fixture Test 2") { fixture => }
property("Fixture Test 3") { fixture => }
}
class ExampleParallelTestExecutionSuiteTimeoutWordSpecPair extends SuiteTimeoutSuites {
def suite1 = new ExampleParallelTestExecutionSuiteTimeoutWordSpec
def suite2 = new ExampleParallelTestExecutionSuiteTimeoutFixtureWordSpec
val holdingSuiteId = suite1.suiteId
val holdingTestName = "Scope 2 should Test 4"
val holdingScopeClosedName = Some("Scope 2")
val holdUntilEventCount = 24
def assertSuiteTimeoutTest(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")
checkSuiteStarting(events(10), suite2.suiteId)
checkScopeOpened(events(11), "Fixture Scope 1")
checkTestStarting(events(12), "Fixture Scope 1 should Fixture Test 1")
checkTestSucceeded(events(13), "Fixture Scope 1 should Fixture Test 1")
checkTestStarting(events(14), "Fixture Scope 1 should Fixture Test 2")
checkTestSucceeded(events(15), "Fixture Scope 1 should Fixture Test 2")
checkScopeClosed(events(16), "Fixture Scope 1")
checkScopeOpened(events(17), "Fixture Scope 2")
checkTestStarting(events(18), "Fixture Scope 2 should Fixture Test 3")
checkTestSucceeded(events(19), "Fixture Scope 2 should Fixture Test 3")
checkTestStarting(events(20), "Fixture Scope 2 should Fixture Test 4")
checkTestSucceeded(events(21), "Fixture Scope 2 should Fixture Test 4")
checkScopeClosed(events(22), "Fixture Scope 2")
checkSuiteCompleted(events(23), suite2.suiteId)
checkTestStarting(events(24), "Scope 2 should Test 4")
checkTestSucceeded(events(25), "Scope 2 should Test 4")
checkScopeClosed(events(26), "Scope 2")
checkSuiteCompleted(events(27), suite1.suiteId)
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutWordSpec extends WordSpec with ParallelTestExecution with SuiteTimeoutSetting {
"Scope 1" should {
"Test 1" in {}
"Test 2" in {}
}
"Scope 2" should {
"Test 3" in {}
"Test 4" in {}
}
}
@DoNotDiscover
class ExampleParallelTestExecutionSuiteTimeoutFixtureWordSpec extends fixture.WordSpec with ParallelTestExecution with SuiteTimeoutSetting with StringFixture {
"Fixture Scope 1" should {
"Fixture Test 1" in { fixture => }
"Fixture Test 2" in { fixture => }
}
"Fixture Scope 2" should {
"Fixture Test 3" in { fixture => }
"Fixture Test 4" in { fixture => }
}
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/HashingEquality.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
/**
* An <code>Equality[T]</code> that offers a <code>hashCodeFor</code> method that
* can provide an <code>Int</code> hash code for a given <code>T</code> instance, whose
* contract is constrainted by that of <code>areEqual</code>.
*
* <p>
* The general contract of <code>hashCodeFor</code> is:
* </p>
*
* <ul>
* <li>
* Whenever <code>hashCodeFor</code> is passed on the same object more than once during an execution an application,
* <code>hashCodeFor</code> must consistently return the same integer, provided no information used in <code>areEqual</code>
* comparisons on the object is modified. This integer need not remain consistent from one execution of an application
* to another execution of the same application.
* </li>
* <li>
* If two objects are equal according to the <code>areEqual</code> method, then passing either of those objects to
* the <code>hashCodeFor</code> method must produce the same integer result.
* </li>
* <li>
* It is not required that if two objects are unequal according to the <code>areEqual</code> method, then calling the
* <code>hashCodeFor</code> method on each of the two objects must produce distinct integer results. However, you should
* be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
* </p>
*
* <p>
* Trait <code>HashingEquality</code> is used by instances of <a href="EquaPath$EquaSet.html"><code>EquaPath#EquaSet</code></a> to implement hash sets based
* on custom equalities.
* </p>
*/
trait HashingEquality[T] extends Equality[T] {
/**
* Returns a hash code for the specified object that is consistent with <code>areEqual</code>.
*
* <p>
* See the main documentation of this trait for more detail on the contract of <code>hashCodeFor</code>.
* </p>
*/
def hashCodeFor(a: T): Int
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/laws/WillEqual.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.matchers._
import org.scalatest.enablers._
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import scala.util.matching.Regex
import java.lang.reflect.Field
import scala.reflect.Manifest
import MatchersHelper.transformOperatorChars
import scala.collection.Traversable
import Assertions.areEqualComparingArraysStructurally
import scala.collection.GenTraversable
import scala.collection.GenSeq
import scala.collection.GenMap
import org.scalactic.Tolerance
import org.scalactic.Explicitly
import org.scalactic.EqualityPolicy.Spread
import org.scalactic.EqualityPolicy.TripleEqualsInvocation
import org.scalactic.Equality
import org.scalactic.EqualityPolicy.TripleEqualsInvocationOnSpread
import org.scalactic.EqualityConstraint
import org.scalactic.Prettifier
import org.scalactic.Every
import MatchersHelper.andMatchersAndApply
import MatchersHelper.orMatchersAndApply
import org.scalatest.words._
import MatchersHelper.matchSymbolToPredicateMethod
import MatchersHelper.accessProperty
import MatchersHelper.newTestFailedException
import MatchersHelper.fullyMatchRegexWithGroups
import MatchersHelper.startWithRegexWithGroups
import MatchersHelper.endWithRegexWithGroups
import MatchersHelper.includeRegexWithGroups
import org.scalactic.NormalizingEquality
import Assertions.checkExpectedException
import Assertions.checkNoException
import exceptions.StackDepthExceptionHelper.getStackDepthFun
import exceptions.NotAllowedException
import scala.language.experimental.macros
import scala.language.higherKinds
import exceptions.TestFailedException
trait WillEqual { willEqual =>
import scala.language.implicitConversions
/**
* This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="Matchers.html"><code>Matchers</code></a> for an overview of
* the matchers DSL.
*
* <p>
* This class is used in conjunction with an implicit conversion to enable <code>will</code> methods to
* be invoked on objects of type <code>Any</code>.
* </p>
*
* @author <NAME>
*/
sealed class AnyWillEqualWrapper[T](val leftSideValue: T) {
/**
* This method enables syntax such as the following:
*
* <pre class="stHighlight">
* a willEqual b
* ^
* </pre>
*/
def willEqual[R](right: R)(implicit evidence: EqualityConstraint[T, R]): Fact = {
val (leftee, rightee) = Suite.getObjectsForFailureMessage(leftSideValue, right)
if (evidence.areEqual(leftSideValue, right)) {
Yes(
Resources.rawDidNotEqual,
Resources.rawEqualed,
Resources.rawDidNotEqual,
Resources.rawEqualed,
Vector(leftee, rightee),
Vector(leftee, rightee),
Vector(leftee, rightee),
Vector(leftee, rightee)
)
}
else {
No(
Resources.rawDidNotEqual,
Resources.rawEqualed,
Resources.rawDidNotEqual,
Resources.rawEqualed,
Vector(leftee, rightee),
Vector(leftee, rightee),
Vector(leftee, rightee),
Vector(leftee, rightee)
)
}
}
}
implicit def convertToAnyWillEqualWrapper[T](o: T): AnyWillEqualWrapper[T] = new AnyWillEqualWrapper(o)
}
object WillEqual extends WillEqual
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/LazyBagSpec.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
class LazyBagSpec extends UnitSpec {
"LazyBag" should "offer a size method" in {
LazyBag(1, 2, 3).size shouldBe 3
LazyBag(1, 1, 3, 2).size shouldBe 4
LazyBag(1, 1, 1, 1).size shouldBe 4
}
it should "have a pretty toString" in {
def assertPretty[T](lazyBag: LazyBag[T]) = {
val lbs = lazyBag.toString
lbs should startWith ("LazyBag(")
lbs should endWith (")")
/*
scala> lbs.replaceAll(""".*\((.*)\).*""", "$1")
res0: String = 1,2,3
scala> res0.split(',')
res1: Array[String] = Array(1, 2, 3)
scala> val lbs = "LazyBag()"
lbs: String = LazyBag()
scala> lbs.replaceAll(""".*\((.*)\).*""", "$1")
res2: String = ""
scala> res2.split(',')
res3: Array[String] = Array("")
*/
val elemStrings = lbs.replaceAll(""".*\((.*)\).*""", "$1")
val elemStrArr = if (elemStrings.size != 0) elemStrings.split(',') else Array.empty[String]
elemStrArr.size should equal (lazyBag.size)
elemStrArr should contain theSameElementsAs lazyBag.toList.map(_.toString)
}
// Test BasicLazyBag
assertPretty(LazyBag(1, 2, 3))
assertPretty(LazyBag(1, 2, 3, 4))
assertPretty(LazyBag(1))
assertPretty(LazyBag())
assertPretty(LazyBag("one", "two", "three", "four", "five"))
// Test FlatMappedLazyBag
val trimmed = EquaPath[String](StringNormalizations.trimmed.toHashingEquality)
val lazyBag = trimmed.EquaSet("1", "2", "01", "3").toLazy
val flatMapped = lazyBag.flatMap { (digit: String) =>
LazyBag(digit.toInt)
}
assertPretty(flatMapped)
val mapped = flatMapped.map(_ + 1)
assertPretty(mapped)
}
it should "have a zip method" in {
val bag1 = LazyBag(1,2,3)
val bag2 = LazyBag("a", "b", "c")
val zipped = bag1.zip(bag2)
val (b1, b2) = zipped.toList.unzip
b1 should contain theSameElementsAs bag1.toList
b2 should contain theSameElementsAs bag2.toList
}
it should "have a zipAll method" in {
val shortBag1 = LazyBag(1,2,3)
val longBag1 = LazyBag(1,2,3,4)
val shortBag2 = LazyBag("a", "b", "c")
val longBag2 = LazyBag("a", "b", "c", "d")
def assertSameElements(thisBag: LazyBag[_], thatBag: LazyBag[_]): Unit = {
val zipped = thisBag.zipAll(thatBag, 4, "d")
val (unzip1, unzip2) = zipped.toList.unzip
unzip1 should contain theSameElementsAs longBag1.toList
unzip2 should contain theSameElementsAs longBag2.toList
}
assertSameElements(shortBag1, longBag2)
assertSameElements(longBag1, shortBag2)
assertSameElements(longBag1, longBag2)
}
it should "have a zipWithIndex method" in {
val bag = LazyBag("a", "b", "c")
val zipped = bag.zipWithIndex
val (b1, b2) = zipped.toList.unzip
b1 should contain theSameElementsAs bag.toList
b2 should contain theSameElementsAs List(0, 1, 2)
}
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/StrictEnabledEquality.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 EqualityPolicy._
trait StrictEnabledEquality extends EnabledEquality {
import scala.language.implicitConversions
// Inherit the Scaladoc for these methods
override def numericEqualityConstraint[A, B](implicit equalityOfA: Equality[A], numA: CooperatingNumeric[A], numB: CooperatingNumeric[B]): EqualityConstraint[A, B] with NativeSupport = new BasicEqualityConstraint[A, B](equalityOfA)
override def booleanEqualityConstraint[A, B](implicit equalityOfA: Equality[A], boolA: CooperatingBoolean[A], boolB: CooperatingBoolean[B]): EqualityConstraint[A, B] with NativeSupport = new BasicEqualityConstraint[A, B](equalityOfA)
implicit def enabledEqualityForChar: EnabledEqualityFor[Char] = EnabledEqualityFor[Char]
implicit def enabledEqualityForByte: EnabledEqualityFor[Byte] = EnabledEqualityFor[Byte]
implicit def enabledEqualityForShort: EnabledEqualityFor[Short] = EnabledEqualityFor[Short]
implicit def enabledEqualityForInt: EnabledEqualityFor[Int] = EnabledEqualityFor[Int]
implicit def enabledEqualityForLong: EnabledEqualityFor[Long] = EnabledEqualityFor[Long]
implicit def enabledEqualityForFloat: EnabledEqualityFor[Float] = EnabledEqualityFor[Float]
implicit def enabledEqualityForDouble: EnabledEqualityFor[Double] = EnabledEqualityFor[Double]
implicit def enabledEqualityForBigInt: EnabledEqualityFor[BigInt] = EnabledEqualityFor[BigInt]
implicit def enabledEqualityForBigDecimal: EnabledEqualityFor[BigDecimal] = EnabledEqualityFor[BigDecimal]
implicit def enabledEqualityForJavaCharacter: EnabledEqualityFor[java.lang.Character] = EnabledEqualityFor[java.lang.Character]
implicit def enabledEqualityForJavaByte: EnabledEqualityFor[java.lang.Byte] = EnabledEqualityFor[java.lang.Byte]
implicit def enabledEqualityForJavaShort: EnabledEqualityFor[java.lang.Short] = EnabledEqualityFor[java.lang.Short]
implicit def enabledEqualityForJavaInteger: EnabledEqualityFor[java.lang.Integer] = EnabledEqualityFor[java.lang.Integer]
implicit def enabledEqualityForJavaLong: EnabledEqualityFor[java.lang.Long] = EnabledEqualityFor[java.lang.Long]
implicit def enabledEqualityForJavaFloat: EnabledEqualityFor[java.lang.Float] = EnabledEqualityFor[java.lang.Float]
implicit def enabledEqualityForJavaDouble: EnabledEqualityFor[java.lang.Double] = EnabledEqualityFor[java.lang.Double]
implicit def enabledEqualityForBoolean: EnabledEqualityFor[Boolean] = EnabledEqualityFor[Boolean]
implicit def enabledEqualityForJavaBoolean: EnabledEqualityFor[java.lang.Boolean] = EnabledEqualityFor[java.lang.Boolean]
}
object StrictEnabledEquality extends StrictEnabledEquality
|
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/algebra/AssociativeSpec.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.algebra
import org.scalactic.UnitSpec
import org.scalactic.Every
class AssociativeSpec extends UnitSpec {
// Every Associative
class EveryAssociative[A] extends Associative[Every[A]] {
def op(a: Every[A], b: Every[A]): Every[A] = a ++ b
}
// Int Multiplication Associatvie
class IntMultiAssociative extends Associative[Int] {
def op(a: Int, b: Int): Int = a * b
}
"An Every Associative (Semigroup)" should "have a binary associative op" in {
implicit val assoc = new EveryAssociative[Int]
import Associative.adapters
val a = Every(1,2)
val b = Every(5,6,7)
val c = Every(9,9)
((a op b) op c) shouldEqual (a op (b op c))
}
"An Int Associative (Semigroup)" should "have a binary associative op" in {
implicit val assoc = new IntMultiAssociative
import Associative.adapters
val intAssoc = new IntMultiAssociative()
// val a = new Associative.Adapter(1)(intAssoc)
val a = 1
val b = 64
val c = 256
((a op b) op c) shouldEqual (a op (b op c))
}
"A BadSubstractionAssociative" should "fail to be associative" in {
// Bad case Substraction Associative, should fail.
class BadSubstractionAssociative extends Associative[Int] {
def op(a: Int, b: Int): Int = a - b
}
implicit val assoc = new BadSubstractionAssociative
import Associative.adapters
val badSubAssoc = new BadSubstractionAssociative()
val a = 1
val b = 64
val c = 256
((a op b) op c) should not be (a op (b op c))
}
"Associative" should "offer an op method directly" in {
val a = Every(1,2)
val b = Every(5,6,7)
val c = Every(9,9)
val assoc = new EveryAssociative[Int]
import assoc.op
op(op(a, b), c) shouldEqual op(a, op(b, c))
}
it should "provide an parameterless apply method in its companion to summon an implicit" in {
implicit val assoc = new IntMultiAssociative
assoc should be theSameInstanceAs implicitly[Associative[Int]]
assoc should be theSameInstanceAs Associative[Int]
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/matchers/MatchSucceeded.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
/**
* Singleton object that provides <code>unapply</code> method to extract negated failure message from <code>MatchResult</code>
* having <code>matches</code> property value of <code>true</code>.
*
* @author <NAME>
* @author <NAME>
*/
object MatchSucceeded {
/**
* Extractor enabling patterns that match <code>MatchResult</code> having <code>matches</code> property value of <code>true</code>,
* extracting the contained negated failure message.
*
* <p>
* For example, you can use this extractor to get the negated failure message of a <code>MatchResult</code> like this:
* </p>
*
* <pre>
* matchResult match {
* case MatchSucceeded(negatedFailureMessage) => // do something with negatedFailureMessage
* case _ => // when matchResult.matches equal to <code>false</code>
* }
* </pre>
*
* @param matchResult the <code>MatchResult</code> to extract the negated failure message from.
* @return a <code>Some</code> wrapping the contained negated failure message if <code>matchResult.matches</code> is equal to <code>true</code>, else <code>None</code>.
*/
def unapply(matchResult: MatchResult): Option[String] =
if (matchResult.matches) Some(matchResult.negatedFailureMessage) else None
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/LazyBag.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 LazyBag[+T] {
def map[U](f: T => U): LazyBag[U]
def flatMap[U](f: T => LazyBag[U]): LazyBag[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]): LazyBag[(T, U)]
def zipAll[U, T1 >: T](that: LazyBag[U], thisElem: T1, thatElem: U): LazyBag[(T1, U)]
def zipWithIndex: LazyBag[(T, Int)]
}
object LazyBag {
private class BasicLazyBag[T](private val args: List[T]) extends LazyBag[T] { thisLazyBag =>
def map[U](f: T => U): LazyBag[U] = new MapLazyBag(thisLazyBag, f)
def flatMap[U](f: T => LazyBag[U]): LazyBag[U] = new FlatMapLazyBag(thisLazyBag, f)
def toEquaSet[U >: T](toPath: EquaPath[U]): toPath.FastEquaSet = toPath.FastEquaSet(args: _*)
def toSortedEquaSet[U >: T](toPath: SortedEquaPath[U]): toPath.SortedEquaSet = ???
def toList: List[T] = args
def size: Int = args.size
def zip[U](thatLazyBag: LazyBag[U]): LazyBag[(T, U)] = new ZipLazyBag(thisLazyBag, thatLazyBag)
def zipAll[U, T1 >: T](that: LazyBag[U], thisElem: T1, thatElem: U): LazyBag[(T1, U)] =
new ZipAllLazyBag(thisLazyBag, that, thisElem, thatElem)
def zipWithIndex: LazyBag[(T, Int)] = new ZipWithIndex(thisLazyBag)
override def toString = args.mkString("LazyBag(", ",", ")")
/* // Don't uncomment unless have a failing test
override def equals(other: Any): Boolean =
other match {
case otherLazyBag: LazyBag[_] =>
thisLazyBag.toList.groupBy(o => o) == otherLazyBag.toList.groupBy(o => o)
case _ => false
}
override def hashCode: Int = thisLazyBag.toList.groupBy(o => o).hashCode
*/
}
private abstract class TransformLazyBag[T, U] extends LazyBag[U] { thisLazyBag =>
def map[V](g: U => V): LazyBag[V] = new MapLazyBag[U, V](thisLazyBag, g)
def flatMap[V](f: U => LazyBag[V]): LazyBag[V] = ???
def toEquaSet[V >: U](toPath: EquaPath[V]): toPath.FastEquaSet = {
toPath.FastEquaSet(toList: _*)
}
def toSortedEquaSet[V >: U](toPath: SortedEquaPath[V]): toPath.SortedEquaSet = ???
def toList: List[U] // This is the lone abstract method
def size: Int = toList.size
def zip[V](that: LazyBag[V]): LazyBag[(U, V)] = new ZipLazyBag[U, V](thisLazyBag, that)
def zipAll[V, U1 >: U](that: LazyBag[V], thisElem: U1, thatElem: V): LazyBag[(U1, V)] =
new ZipAllLazyBag(thisLazyBag, that, thisElem, thatElem)
def zipWithIndex: LazyBag[(U, Int)] = new ZipWithIndex(thisLazyBag)
override def toString: String = toList.mkString("LazyBag(", ",", ")")
override def equals(other: Any): Boolean =
other match {
case otherLazyBag: LazyBag[_] =>
thisLazyBag.toList.groupBy(o => o) == otherLazyBag.toList.groupBy(o => o)
case _ => false
}
override def hashCode: Int = thisLazyBag.toList.groupBy(o => o).hashCode
}
private class MapLazyBag[T, U](lazyBag: LazyBag[T], f: T => U) extends TransformLazyBag[T, U] {
def toList: List[U] = lazyBag.toList.map(f)
}
private class FlatMapLazyBag[T, U](lazyBag: LazyBag[T], f: T => LazyBag[U]) extends TransformLazyBag[T, U] {
def toList: List[U] = lazyBag.toList.flatMap(f.andThen(_.toList))
}
private class ZipLazyBag[T, U](lazyBag: LazyBag[T], that: LazyBag[U]) extends TransformLazyBag[T, (T, U)] {
def toList: List[(T, U)] = lazyBag.toList.zip(that.toList)
}
private class ZipAllLazyBag[T, U](thisBag: LazyBag[T], thatBag: LazyBag[U], thisElem: T, thatElem: U) extends TransformLazyBag[T, (T, U)] {
def toList: List[(T, U)] = thisBag.toList.zipAll(thatBag.toList, thisElem, thatElem)
}
private class ZipWithIndex[T, U](thisBag: LazyBag[T]) extends TransformLazyBag[T, (T, Int)] {
def toList: List[(T, Int)] = thisBag.toList.zipWithIndex
}
def apply[T](args: T*): LazyBag[T] = new BasicLazyBag(args.toList)
}
|
cquiroz/scalatest | scalactic-macro/src/main/scala/org/scalactic/anyvals/Percent.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
// These are here emporaritly for testing, because need to have the compile separate. Can't I just move them?
private[scalactic] final class Percent private (val value: Int) extends AnyVal {
override def toString: String = s"Percent($value)"
}
private[scalactic] object Percent {
def from(value: Int): Option[Percent] =
if (value >= 0 && value <= 100) Some(new Percent(value)) else None
import scala.language.experimental.macros
def apply(value: Int): Percent = macro PercentMacro.apply
}
private[scalactic] final class LPercent private (val value: Long) extends AnyVal {
override def toString: String = s"LPercent($value)"
}
private[scalactic] object LPercent {
def from(value: Long): Option[LPercent] =
if (value >= 0L && value <= 100L) Some(new LPercent(value)) else None
}
private[scalactic] final class FPercent private (val value: Float) extends AnyVal {
override def toString: String = s"FPercent($value)"
}
private[scalactic] object FPercent {
def from(value: Float): Option[FPercent] =
if (value >= 0.0F && value <= 100.0F) Some(new FPercent(value)) else None
}
private[scalactic] final class DPercent private (val value: Double) extends AnyVal {
override def toString: String = s"DPercent($value)"
}
private[scalactic] object DPercent {
def from(value: Double): Option[DPercent] =
if (value >= 0.0 && value <= 100.0) Some(new DPercent(value)) else None
}
private[scalactic] final class TLA private (val value: String) extends AnyVal {
override def toString: String = s"TLA($value)"
}
private[scalactic] object TLA {
def from(value: String): Option[TLA] =
if (value.length == 3) Some(new TLA(value)) else None
import scala.language.experimental.macros
def apply(value: String): TLA = macro TLAMacro.apply
}
private[scalactic] final class Digit private (val value: Char) extends AnyVal {
override def toString: String = s"Digit($value)"
}
private[scalactic] object Digit {
def from(value: Char): Option[Digit] =
if (value >= '0' && value <= '9') Some(new Digit(value)) else None
import scala.language.experimental.macros
def apply(value: Char): Digit = macro DigitMacro.apply
}
|
cquiroz/scalatest | scalatest.js/src/main/scala/org/scalatest/tools/TaskRunner.scala | package org.scalatest.tools
import org.scalatest.events.{TestFailed,
ExceptionalEvent,
Event,
SuiteStarting,
TopOfClass,
SuiteCompleted,
SuiteAborted,
SeeStackDepthException}
import org.scalatest.tools.StringReporter._
import sbt.testing._
import org.scalajs.testinterface.TestUtils
import org.scalatest.{Suite, Args, Tracker}
import java.util.concurrent.atomic.AtomicInteger
import scala.compat.Platform
final class TaskRunner(task: TaskDef,
cl: ClassLoader,
tracker: Tracker,
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean,
notifyServer: Option[String => Unit]) extends Task {
def tags(): Array[String] = Array.empty
def taskDef(): TaskDef = task
def execute(eventHandler: EventHandler, loggers: Array[Logger], continuation: (Array[Task]) => Unit): Unit = {
continuation(execute(eventHandler, loggers))
}
def execute(eventHandler: EventHandler, loggers: Array[Logger]): Array[Task] = {
val suiteStartTime = Platform.currentTime
val suite = TestUtils.newInstance(task.fullyQualifiedName, cl)(Seq.empty).asInstanceOf[Suite]
val sbtLogInfoReporter = new SbtLogInfoReporter(
loggers,
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
notifyServer
)
val formatter = Suite.formatterForSuiteStarting(suite)
val suiteClass = suite.getClass
val reporter = new SbtReporter(suite.suiteId, task.fullyQualifiedName, task.fingerprint, eventHandler, sbtLogInfoReporter)
if (!suite.isInstanceOf[DistributedTestRunnerSuite])
reporter(SuiteStarting(tracker.nextOrdinal(), suite.suiteName, suite.suiteId, Some(suiteClass.getName), formatter, Some(TopOfClass(suiteClass.getName))))
try {
suite.run(None, Args(reporter))
val formatter = Suite.formatterForSuiteCompleted(suite)
val duration = Platform.currentTime
if (!suite.isInstanceOf[DistributedTestRunnerSuite])
reporter(SuiteCompleted(tracker.nextOrdinal(), suite.suiteName, suite.suiteId, Some(suiteClass.getName), Some(duration), formatter, Some(TopOfClass(suiteClass.getName))))
} catch {
case e: Throwable =>
val rawString = "Exception encountered when attempting to run a suite with class name: " + suiteClass.getName
val formatter = Suite.formatterForSuiteAborted(suite, rawString)
val duration = Platform.currentTime - suiteStartTime
// Do fire SuiteAborted even if a DistributedTestRunnerSuite, consistent with SuiteRunner behavior
reporter(SuiteAborted(tracker.nextOrdinal(), rawString, suite.suiteName, suite.suiteId, Some(suiteClass.getName), Some(e), Some(duration), formatter, Some(SeeStackDepthException)))
}
Array.empty
}
private class SbtLogInfoReporter(
loggers: Array[Logger],
presentAllDurations: Boolean,
presentInColor: Boolean,
presentShortStackTraces: Boolean,
presentFullStackTraces: Boolean,
presentUnformatted: Boolean,
presentReminder: Boolean,
presentReminderWithShortStackTraces: Boolean,
presentReminderWithFullStackTraces: Boolean,
presentReminderWithoutCanceledTests: Boolean,
notifyServer: Option[String => Unit]
) extends StringReporter(
presentAllDurations,
presentInColor,
presentShortStackTraces,
presentFullStackTraces,
presentUnformatted,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests
) {
protected def printPossiblyInColor(fragment: Fragment) {
loggers.foreach { logger =>
logger.info(fragment.toPossiblyColoredText(logger.ansiCodesSupported && presentInColor))
}
}
override def apply(event: Event) {
/*event match {
case ee: ExceptionalEvent if presentReminder =>
if (!presentReminderWithoutCanceledTests || event.isInstanceOf[TestFailed]) {
summaryCounter.recordReminderEvents(ee)
}
case _ =>
}*/
notifyServer.foreach(send => send(event.getClass.getName))
fragmentsForEvent(
event,
presentUnformatted,
presentAllDurations,
presentShortStackTraces,
presentFullStackTraces,
presentReminder,
presentReminderWithShortStackTraces,
presentReminderWithFullStackTraces,
presentReminderWithoutCanceledTests,
reminderEventsBuf
) foreach printPossiblyInColor
}
def dispose() = ()
}
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/fixture/ExamplePropSpec.scala | package test.fixture
import org.scalatest._
class ExamplePropSpec extends fixture.PropSpec {
type FixtureParam = String
def withFixture(test: OneArgTest): Outcome = {
test("hi")
}
property("an empty Set should have size 0") { f =>
assert(Set.empty[Int].size == 0)
}
} |
cquiroz/scalatest | scalatest.js/src/main/scala/org/scalatest/tools/SbtReporter.scala | package org.scalatest.tools
import sbt.testing.{Status => SbtStatus, _}
import org.scalatest.Reporter
private class SbtReporter(suiteId: String, fullyQualifiedName: String, fingerprint: Fingerprint, eventHandler: EventHandler, report: Reporter) extends Reporter {
import org.scalatest.events._
private def getTestSelector(eventSuiteId: String, testName: String) = {
if (suiteId == eventSuiteId)
new TestSelector(testName)
else
new NestedTestSelector(eventSuiteId, testName)
}
private def getSuiteSelector(eventSuiteId: String) = {
if (suiteId == eventSuiteId)
new SuiteSelector
else
new NestedSuiteSelector(eventSuiteId)
}
private def getOptionalThrowable(throwable: Option[Throwable]): OptionalThrowable =
throwable match {
case Some(t) => new OptionalThrowable(t)
case None => new OptionalThrowable
}
override def apply(event: Event) {
report(event)
event match {
// the results of running an actual test
case t: TestPending =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Pending, new OptionalThrowable, t.duration.getOrElse(0)))
case t: TestFailed =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Failure, getOptionalThrowable(t.throwable), t.duration.getOrElse(0)))
case t: TestSucceeded =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Success, new OptionalThrowable, t.duration.getOrElse(0)))
case t: TestIgnored =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Ignored, new OptionalThrowable, -1))
case t: TestCanceled =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getTestSelector(t.suiteId, t.testName), SbtStatus.Canceled, new OptionalThrowable, t.duration.getOrElse(0)))
case t: SuiteAborted =>
eventHandler.handle(ScalaTestSbtEvent(fullyQualifiedName, fingerprint, getSuiteSelector(t.suiteId), SbtStatus.Error, getOptionalThrowable(t.throwable), t.duration.getOrElse(0)))
case _ =>
}
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ParallelTestExecutionSpec.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.SharedHelpers.EventRecordingReporter
import collection.mutable.ListBuffer
import java.util.concurrent.Executors
import java.util.concurrent.ExecutorService
import org.scalatest.tools.SuiteRunner
import org.scalatest.tools.SuiteSortingReporter
import org.scalatest.events.SuiteStarting
import org.scalatest.events.SuiteCompleted
import org.scalatest.events.InfoProvided
import java.util.concurrent.Future
import java.util.concurrent.LinkedBlockingQueue
import org.scalatest.time.Span
import org.scalatest.time.Second
import org.scalatest.time.Seconds
import java.io.PrintStream
import java.io.ByteArrayOutputStream
import Matchers._
class ParallelTestExecutionSpec extends FunSpec with EventHelpers {
/*
Need 3 tests at least
1. should have the events reported in correct order when tests are executed in parallel
For that one, pass in a Distributor that runs with just one thread and orders things
in a predefined, out of order order.
2. DistributedSuiteSorter should wait for completedTests instead of moving on when it
gets a SuiteCompleted.
3. Both of these should time out. So we need a test for each that shows the timeout
happened. I.e., it will move on when waiting for something.
*/
describe("ParallelTestExecution") {
class ControlledOrderDistributor extends Distributor {
val buf = ListBuffer.empty[(Suite, Args, ScalaTestStatefulStatus)]
def apply(suite: Suite, args: Args): Status = {
val status = new ScalaTestStatefulStatus
buf += ((suite, args, status))
status
}
def executeInOrder() {
for ((suite, args, status) <- buf) {
val runStatus = suite.run(None, args)
if (!runStatus.succeeds())
status.setFailed()
status.setCompleted()
}
}
def executeInReverseOrder() {
for ((suite, args, status) <- buf.reverse) {
val runStatus = suite.run(None, args)
if (!runStatus.succeeds())
status.setFailed()
status.setCompleted()
}
}
def apply(suite: Suite, tracker: Tracker) {
throw new UnsupportedOperationException("Hey, we're not supposed to be calling this anymore!")
}
}
class ControlledOrderConcurrentDistributor(poolSize: Int) extends Distributor {
private val futureQueue = new LinkedBlockingQueue[Future[T] forSome { type T }]
val buf = ListBuffer.empty[SuiteRunner]
val execSvc: ExecutorService = Executors.newFixedThreadPool(2)
def apply(suite: Suite, args: Args): Status = {
val status = new ScalaTestStatefulStatus
buf += new SuiteRunner(suite, args, status)
status
}
def executeInOrder() {
for (suiteRunner <- buf) {
val future: Future[_] = execSvc.submit(suiteRunner)
futureQueue.put(future)
}
while (futureQueue.peek != null)
futureQueue.poll().get()
}
def executeInReverseOrder() {
for (suiteRunner <- buf.reverse) {
val future: Future[_] = execSvc.submit(suiteRunner)
futureQueue.put(future)
}
while (futureQueue.peek != null)
futureQueue.poll().get()
}
def apply(suite: Suite, tracker: Tracker) {
throw new UnsupportedOperationException("Hey, we're not supposed to be calling this anymore!")
}
}
it("should have the events reported in correct order when tests are executed in parallel") {
def withDistributor(fun: ControlledOrderDistributor => Unit) {
val recordingReporter = new EventRecordingReporter
val outOfOrderDistributor = new ControlledOrderDistributor
(new ExampleParallelSpec).run(None, Args(recordingReporter, distributor = Some(outOfOrderDistributor)))
fun(outOfOrderDistributor)
val eventRecorded = recordingReporter.eventsReceived
checkScopeOpened(eventRecorded(0), "Subject 1")
checkTestStarting(eventRecorded(1), "Subject 1 should have behavior 1a")
checkTestSucceeded(eventRecorded(2), "Subject 1 should have behavior 1a")
checkTestStarting(eventRecorded(3), "Subject 1 should have behavior 1b")
checkTestSucceeded(eventRecorded(4), "Subject 1 should have behavior 1b")
checkTestStarting(eventRecorded(5), "Subject 1 should have behavior 1c")
checkTestSucceeded(eventRecorded(6), "Subject 1 should have behavior 1c")
checkScopeClosed(eventRecorded(7), "Subject 1")
checkScopeOpened(eventRecorded(8), "Subject 2")
checkTestStarting(eventRecorded(9), "Subject 2 should have behavior 2a")
checkTestSucceeded(eventRecorded(10), "Subject 2 should have behavior 2a")
checkTestStarting(eventRecorded(11), "Subject 2 should have behavior 2b")
checkTestSucceeded(eventRecorded(12), "Subject 2 should have behavior 2b")
checkTestStarting(eventRecorded(13), "Subject 2 should have behavior 2c")
checkTestSucceeded(eventRecorded(14), "Subject 2 should have behavior 2c")
checkScopeClosed(eventRecorded(15), "Subject 2")
}
withDistributor(_.executeInOrder())
withDistributor(_.executeInReverseOrder())
}
it("should have InfoProvided fired from before and after block in correct order when tests are executed in parallel") {
def withDistributor(fun: ControlledOrderDistributor => Unit) {
val recordingReporter = new EventRecordingReporter
val outOfOrderDistributor = new ControlledOrderDistributor
(new ExampleBeforeAfterParallelSpec).run(None, Args(recordingReporter, distributor = Some(outOfOrderDistributor)))
fun(outOfOrderDistributor)
val eventRecorded = recordingReporter.eventsReceived
assert(eventRecorded.size === 28)
checkScopeOpened(eventRecorded(0), "Thing 1")
checkInfoProvided(eventRecorded(1), "In Before")
checkTestStarting(eventRecorded(2), "Thing 1 do thing 1a")
checkTestSucceeded(eventRecorded(3), "Thing 1 do thing 1a")
checkInfoProvided(eventRecorded(4), "In After")
checkInfoProvided(eventRecorded(5), "In Before")
checkTestStarting(eventRecorded(6), "Thing 1 do thing 1b")
checkTestSucceeded(eventRecorded(7), "Thing 1 do thing 1b")
checkInfoProvided(eventRecorded(8), "In After")
checkInfoProvided(eventRecorded(9), "In Before")
checkTestStarting(eventRecorded(10), "Thing 1 do thing 1c")
checkTestSucceeded(eventRecorded(11), "Thing 1 do thing 1c")
checkInfoProvided(eventRecorded(12), "In After")
checkScopeClosed(eventRecorded(13), "Thing 1")
checkScopeOpened(eventRecorded(14), "Thing 2")
checkInfoProvided(eventRecorded(15), "In Before")
checkTestStarting(eventRecorded(16), "Thing 2 do thing 2a")
checkTestSucceeded(eventRecorded(17), "Thing 2 do thing 2a")
checkInfoProvided(eventRecorded(18), "In After")
checkInfoProvided(eventRecorded(19), "In Before")
checkTestStarting(eventRecorded(20), "Thing 2 do thing 2b")
checkTestSucceeded(eventRecorded(21), "Thing 2 do thing 2b")
checkInfoProvided(eventRecorded(22), "In After")
checkInfoProvided(eventRecorded(23), "In Before")
checkTestStarting(eventRecorded(24), "Thing 2 do thing 2c")
checkTestSucceeded(eventRecorded(25), "Thing 2 do thing 2c")
checkInfoProvided(eventRecorded(26), "In After")
checkScopeClosed(eventRecorded(27), "Thing 2")
}
withDistributor(_.executeInOrder())
withDistributor(_.executeInReverseOrder())
}
it("should have the blocking test's events fired without waiting when timeout reaches, and when the missing event finally reach later, it should just get fired") {
def withDistributor(fun: ControlledOrderConcurrentDistributor => Unit) {
val recordingReporter = new EventRecordingReporter
val args = Args(recordingReporter)
val outOfOrderConcurrentDistributor = new ControlledOrderConcurrentDistributor(2)
(new ExampleTimeoutParallelSpec).run(None, Args(recordingReporter, distributor = Some(outOfOrderConcurrentDistributor)))
fun(outOfOrderConcurrentDistributor)
val eventRecorded = recordingReporter.eventsReceived
assert(eventRecorded.size === 16)
checkScopeOpened(eventRecorded(0), "Thing 1")
checkTestStarting(eventRecorded(1), "Thing 1 do thing 1a")
checkTestSucceeded(eventRecorded(2), "Thing 1 do thing 1a")
checkTestStarting(eventRecorded(3), "Thing 1 do thing 1b")
checkTestStarting(eventRecorded(4), "Thing 1 do thing 1c")
checkTestSucceeded(eventRecorded(5), "Thing 1 do thing 1c")
checkScopeClosed(eventRecorded(6), "Thing 1")
checkScopeOpened(eventRecorded(7), "Thing 2")
checkTestStarting(eventRecorded(8), "Thing 2 do thing 2a")
checkTestSucceeded(eventRecorded(9), "Thing 2 do thing 2a")
checkTestStarting(eventRecorded(10), "Thing 2 do thing 2b")
checkTestSucceeded(eventRecorded(11), "Thing 2 do thing 2b")
checkTestStarting(eventRecorded(12), "Thing 2 do thing 2c")
checkTestSucceeded(eventRecorded(13), "Thing 2 do thing 2c")
checkScopeClosed(eventRecorded(14), "Thing 2")
// Now the missing one.
checkTestSucceeded(eventRecorded(15), "Thing 1 do thing 1b")
}
withDistributor(_.executeInOrder())
withDistributor(_.executeInReverseOrder())
}
// TODO: Check with <NAME>. I'm not sure what this is supposed to be testing, and it fails.
it("should have the events reported in correct order when multiple suite's tests are executed in parallel") {
def withDistributor(fun: ControlledOrderConcurrentDistributor => Unit) = {
val recordingReporter = new EventRecordingReporter
val outOfOrderConcurrentDistributor = new ControlledOrderConcurrentDistributor(2)
val suiteSortingReporter = new SuiteSortingReporter(recordingReporter, Span(5, Seconds), new PrintStream(new ByteArrayOutputStream))
val spec1 = new ExampleParallelSpec()
val spec2 = new ExampleBeforeAfterParallelSpec()
val tracker = new Tracker()
suiteSortingReporter(SuiteStarting(tracker.nextOrdinal, spec1.suiteName, spec1.suiteId, Some(spec1.getClass.getName), None))
suiteSortingReporter(SuiteStarting(tracker.nextOrdinal, spec2.suiteName, spec2.suiteId, Some(spec2.getClass.getName), None))
spec1.run(None, Args(suiteSortingReporter, distributor = Some(outOfOrderConcurrentDistributor), distributedSuiteSorter = Some(suiteSortingReporter)))
spec2.run(None, Args(suiteSortingReporter, distributor = Some(outOfOrderConcurrentDistributor), distributedSuiteSorter = Some(suiteSortingReporter)))
suiteSortingReporter(SuiteCompleted(tracker.nextOrdinal, spec1.suiteName, spec1.suiteId, Some(spec1.getClass.getName), None))
suiteSortingReporter(SuiteCompleted(tracker.nextOrdinal, spec2.suiteName, spec2.suiteId, Some(spec2.getClass.getName), None))
fun(outOfOrderConcurrentDistributor)
recordingReporter.eventsReceived
}
val spec1SuiteId = new ExampleParallelSpec().suiteId
val spec2SuiteId = new ExampleBeforeAfterParallelSpec().suiteId
val inOrderEvents = withDistributor(_.executeInOrder)
assert(inOrderEvents.size === 48)
checkSuiteStarting(inOrderEvents(0), spec1SuiteId)
checkScopeOpened(inOrderEvents(1), "Subject 1")
checkTestStarting(inOrderEvents(2), "Subject 1 should have behavior 1a")
checkTestSucceeded(inOrderEvents(3), "Subject 1 should have behavior 1a")
checkTestStarting(inOrderEvents(4), "Subject 1 should have behavior 1b")
checkTestSucceeded(inOrderEvents(5), "Subject 1 should have behavior 1b")
checkTestStarting(inOrderEvents(6), "Subject 1 should have behavior 1c")
checkTestSucceeded(inOrderEvents(7), "Subject 1 should have behavior 1c")
checkScopeClosed(inOrderEvents(8), "Subject 1")
checkScopeOpened(inOrderEvents(9), "Subject 2")
checkTestStarting(inOrderEvents(10), "Subject 2 should have behavior 2a")
checkTestSucceeded(inOrderEvents(11), "Subject 2 should have behavior 2a")
checkTestStarting(inOrderEvents(12), "Subject 2 should have behavior 2b")
checkTestSucceeded(inOrderEvents(13), "Subject 2 should have behavior 2b")
checkTestStarting(inOrderEvents(14), "Subject 2 should have behavior 2c")
checkTestSucceeded(inOrderEvents(15), "Subject 2 should have behavior 2c")
checkScopeClosed(inOrderEvents(16), "Subject 2")
checkSuiteCompleted(inOrderEvents(17), spec1SuiteId)
checkSuiteStarting(inOrderEvents(18), spec2SuiteId)
checkScopeOpened(inOrderEvents(19), "Thing 1")
checkInfoProvided(inOrderEvents(20), "In Before")
checkTestStarting(inOrderEvents(21), "Thing 1 do thing 1a")
checkTestSucceeded(inOrderEvents(22), "Thing 1 do thing 1a")
checkInfoProvided(inOrderEvents(23), "In After")
checkInfoProvided(inOrderEvents(24), "In Before")
checkTestStarting(inOrderEvents(25), "Thing 1 do thing 1b")
checkTestSucceeded(inOrderEvents(26), "Thing 1 do thing 1b")
checkInfoProvided(inOrderEvents(27), "In After")
checkInfoProvided(inOrderEvents(28), "In Before")
checkTestStarting(inOrderEvents(29), "Thing 1 do thing 1c")
checkTestSucceeded(inOrderEvents(30), "Thing 1 do thing 1c")
checkInfoProvided(inOrderEvents(31), "In After")
checkScopeClosed(inOrderEvents(32), "Thing 1")
checkScopeOpened(inOrderEvents(33), "Thing 2")
checkInfoProvided(inOrderEvents(34), "In Before")
checkTestStarting(inOrderEvents(35), "Thing 2 do thing 2a")
checkTestSucceeded(inOrderEvents(36), "Thing 2 do thing 2a")
checkInfoProvided(inOrderEvents(37), "In After")
checkInfoProvided(inOrderEvents(38), "In Before")
checkTestStarting(inOrderEvents(39), "Thing 2 do thing 2b")
checkTestSucceeded(inOrderEvents(40), "Thing 2 do thing 2b")
checkInfoProvided(inOrderEvents(41), "In After")
checkInfoProvided(inOrderEvents(42), "In Before")
checkTestStarting(inOrderEvents(43), "Thing 2 do thing 2c")
checkTestSucceeded(inOrderEvents(44), "Thing 2 do thing 2c")
checkInfoProvided(inOrderEvents(45), "In After")
checkScopeClosed(inOrderEvents(46), "Thing 2")
checkSuiteCompleted(inOrderEvents(47), spec2SuiteId)
val reverseOrderEvents = withDistributor(_.executeInReverseOrder)
assert(reverseOrderEvents.size === 48)
checkSuiteStarting(reverseOrderEvents(0), spec1SuiteId)
checkScopeOpened(reverseOrderEvents(1), "Subject 1")
checkTestStarting(reverseOrderEvents(2), "Subject 1 should have behavior 1a")
checkTestSucceeded(reverseOrderEvents(3), "Subject 1 should have behavior 1a")
checkTestStarting(reverseOrderEvents(4), "Subject 1 should have behavior 1b")
checkTestSucceeded(reverseOrderEvents(5), "Subject 1 should have behavior 1b")
checkTestStarting(reverseOrderEvents(6), "Subject 1 should have behavior 1c")
checkTestSucceeded(reverseOrderEvents(7), "Subject 1 should have behavior 1c")
checkScopeClosed(reverseOrderEvents(8), "Subject 1")
checkScopeOpened(reverseOrderEvents(9), "Subject 2")
checkTestStarting(reverseOrderEvents(10), "Subject 2 should have behavior 2a")
checkTestSucceeded(reverseOrderEvents(11), "Subject 2 should have behavior 2a")
checkTestStarting(reverseOrderEvents(12), "Subject 2 should have behavior 2b")
checkTestSucceeded(reverseOrderEvents(13), "Subject 2 should have behavior 2b")
checkTestStarting(reverseOrderEvents(14), "Subject 2 should have behavior 2c")
checkTestSucceeded(reverseOrderEvents(15), "Subject 2 should have behavior 2c")
checkScopeClosed(reverseOrderEvents(16), "Subject 2")
checkSuiteCompleted(reverseOrderEvents(17), spec1SuiteId)
checkSuiteStarting(reverseOrderEvents(18), spec2SuiteId)
checkScopeOpened(reverseOrderEvents(19), "Thing 1")
checkInfoProvided(reverseOrderEvents(20), "In Before")
checkTestStarting(reverseOrderEvents(21), "Thing 1 do thing 1a")
checkTestSucceeded(reverseOrderEvents(22), "Thing 1 do thing 1a")
checkInfoProvided(reverseOrderEvents(23), "In After")
checkInfoProvided(reverseOrderEvents(24), "In Before")
checkTestStarting(reverseOrderEvents(25), "Thing 1 do thing 1b")
checkTestSucceeded(reverseOrderEvents(26), "Thing 1 do thing 1b")
checkInfoProvided(reverseOrderEvents(27), "In After")
checkInfoProvided(reverseOrderEvents(28), "In Before")
checkTestStarting(reverseOrderEvents(29), "Thing 1 do thing 1c")
checkTestSucceeded(reverseOrderEvents(30), "Thing 1 do thing 1c")
checkInfoProvided(reverseOrderEvents(31), "In After")
checkScopeClosed(reverseOrderEvents(32), "Thing 1")
checkScopeOpened(reverseOrderEvents(33), "Thing 2")
checkInfoProvided(reverseOrderEvents(34), "In Before")
checkTestStarting(reverseOrderEvents(35), "Thing 2 do thing 2a")
checkTestSucceeded(reverseOrderEvents(36), "Thing 2 do thing 2a")
checkInfoProvided(reverseOrderEvents(37), "In After")
checkInfoProvided(reverseOrderEvents(38), "In Before")
checkTestStarting(reverseOrderEvents(39), "Thing 2 do thing 2b")
checkTestSucceeded(reverseOrderEvents(40), "Thing 2 do thing 2b")
checkInfoProvided(reverseOrderEvents(41), "In After")
checkInfoProvided(reverseOrderEvents(42), "In Before")
checkTestStarting(reverseOrderEvents(43), "Thing 2 do thing 2c")
checkTestSucceeded(reverseOrderEvents(44), "Thing 2 do thing 2c")
checkInfoProvided(reverseOrderEvents(45), "In After")
checkScopeClosed(reverseOrderEvents(46), "Thing 2")
checkSuiteCompleted(reverseOrderEvents(47), spec2SuiteId)
}
it("should have the blocking suite's events fired without waiting when timeout reaches, and when the missing event finally reach later, it should just get fired") {
val recordingReporter = new EventRecordingReporter
val args = Args(recordingReporter)
val outOfOrderConcurrentDistributor = new ControlledOrderConcurrentDistributor(2)
val suiteSortingReporter = new SuiteSortingReporter(recordingReporter, Span(1, Second), new PrintStream(new ByteArrayOutputStream))
val spec1 = new ExampleSuiteTimeoutSpec()
val spec2 = new ExampleSuiteTimeoutSpec2()
val tracker = new Tracker()
suiteSortingReporter(SuiteStarting(tracker.nextOrdinal, spec1.suiteName, spec1.suiteId, Some(spec1.getClass.getName), None))
suiteSortingReporter(SuiteStarting(tracker.nextOrdinal, spec2.suiteName, spec2.suiteId, Some(spec2.getClass.getName), None))
spec1.run(None, Args(suiteSortingReporter, distributor = Some(outOfOrderConcurrentDistributor), distributedSuiteSorter = Some(suiteSortingReporter)))
spec2.run(None, Args(suiteSortingReporter, distributor = Some(outOfOrderConcurrentDistributor), distributedSuiteSorter = Some(suiteSortingReporter)))
suiteSortingReporter(SuiteCompleted(tracker.nextOrdinal, spec1.suiteName, spec1.suiteId, Some(spec1.getClass.getName), None))
suiteSortingReporter(SuiteCompleted(tracker.nextOrdinal, spec2.suiteName, spec2.suiteId, Some(spec2.getClass.getName), None))
outOfOrderConcurrentDistributor.executeInOrder()
val eventRecorded = recordingReporter.eventsReceived
println(eventRecorded.map(e => e.getClass.getName).mkString("\n"))
assert(eventRecorded.size === 34)
checkSuiteStarting(eventRecorded(0), spec1.suiteId)
checkScopeOpened(eventRecorded(1), "Thing 1")
checkTestStarting(eventRecorded(2), "Thing 1 do thing 1a")
checkTestSucceeded(eventRecorded(3), "Thing 1 do thing 1a")
checkTestStarting(eventRecorded(4), "Thing 1 do thing 1b")
checkTestSucceeded(eventRecorded(5), "Thing 1 do thing 1b")
checkTestStarting(eventRecorded(6), "Thing 1 do thing 1c")
checkTestSucceeded(eventRecorded(7), "Thing 1 do thing 1c")
checkScopeClosed(eventRecorded(8), "Thing 1")
checkScopeOpened(eventRecorded(9), "Thing 2")
checkTestStarting(eventRecorded(10), "Thing 2 do thing 2a")
checkTestSucceeded(eventRecorded(11), "Thing 2 do thing 2a")
// SuiteSortingReporter timeout should hit here.
checkSuiteCompleted(eventRecorded(12), spec1.suiteId)
checkSuiteStarting(eventRecorded(13), spec2.suiteId)
checkScopeOpened(eventRecorded(14), "Subject 1")
checkTestStarting(eventRecorded(15), "Subject 1 content 1a")
checkTestSucceeded(eventRecorded(16), "Subject 1 content 1a")
checkTestStarting(eventRecorded(17), "Subject 1 content 1b")
checkTestSucceeded(eventRecorded(18), "Subject 1 content 1b")
checkTestStarting(eventRecorded(19), "Subject 1 content 1c")
checkTestSucceeded(eventRecorded(20), "Subject 1 content 1c")
checkScopeClosed(eventRecorded(21), "Subject 1")
checkScopeOpened(eventRecorded(22), "Subject 2")
checkTestStarting(eventRecorded(23), "Subject 2 content 2a")
checkTestSucceeded(eventRecorded(24), "Subject 2 content 2a")
checkTestStarting(eventRecorded(25), "Subject 2 content 2b")
checkTestSucceeded(eventRecorded(26), "Subject 2 content 2b")
checkTestStarting(eventRecorded(27), "Subject 2 content 2c")
checkTestSucceeded(eventRecorded(28), "Subject 2 content 2c")
checkScopeClosed(eventRecorded(29), "Subject 2")
checkSuiteCompleted(eventRecorded(30), spec2.suiteId)
// Now the missing ones.
checkTestStarting(eventRecorded(31), "Thing 2 do thing 2b")
checkTestSucceeded(eventRecorded(32), "Thing 2 do thing 2b")
checkScopeClosed(eventRecorded(33), "Thing 2")
}
it("should only execute nested suites in outer instance") {
class InnerSuite extends FunSuite {
test("hi") { info("hi info") }
}
class OuterSuite extends FunSuite with ParallelTestExecution {
override def nestedSuites = Vector(new InnerSuite)
test("outer 1") { info("outer 1 info") }
test("outer 2") { info("outer 2 info") }
override def newInstance = new OuterSuite
}
val rep = new EventRecordingReporter
val outer = new OuterSuite
outer.run(None, Args(rep))
assert(rep.testStartingEventsReceived.size === 3)
val testSucceededEvents = rep.testSucceededEventsReceived
assert(testSucceededEvents.size === 3)
testSucceededEvents.foreach { e =>
e.testName match {
case "hi" =>
assert(e.recordedEvents.size === 1)
assert(e.recordedEvents(0).asInstanceOf[InfoProvided].message === "hi info")
case "outer 1" =>
assert(e.recordedEvents.size === 1)
assert(e.recordedEvents(0).asInstanceOf[InfoProvided].message === "outer 1 info")
case "outer 2" =>
assert(e.recordedEvents.size === 1)
assert(e.recordedEvents(0).asInstanceOf[InfoProvided].message === "outer 2 info")
case other =>
fail("Unexpected TestSucceeded event: " + other)
}
}
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/tools/MemoryReporterSuite.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 org.scalatest.events.Ordinal
import org.scalatest.events.TestStarting
import org.scalatest.events.TestFailed
import org.scalatest.events.TestSucceeded
import org.scalatest.events.TestCanceled
import org.scalatest.events.SuiteAborted
import org.scalatest.events.RecordableEvent
import org.scalatest.events.RunCompleted
import org.scalatest.events.RunStarting
import org.scalatest.ConfigMap
import java.io.File
class MemoryReporterSuite extends FunSuite {
val OutputFileName = "target/MemoryReporterSuite.out"
val runComplete =
RunCompleted(new Ordinal(0))
val runStarting =
RunStarting(
new Ordinal(1),
testCount = 3,
configMap = new ConfigMap(Map[String, Any]()))
// testName is set to "Some(say one)" here to verify proper encoding/decoding
// by Memento when name might be confused for an Option
val testStarting1 =
TestStarting(
new Ordinal(2),
suiteName = "org.example.OneSuite",
suiteId = "org.example.OneSuite",
suiteClassName = Some("org.example.OneSuite"),
testName = "Some(say one)",
testText = "say one")
val testFailed =
TestFailed(
new Ordinal(3),
message = "say what?",
suiteName = "org.example.OneSuite",
suiteId = "org.example.OneSuite",
suiteClassName = Some("org.example.OneSuite"),
testName = "Some(say one)",
testText = "say one",
recordedEvents = Vector.empty[RecordableEvent],
rerunner = Some("org.example.OneSuite"))
val testStarting2 =
TestStarting(
new Ordinal(4),
suiteName = "org.example.YourSuite",
suiteId = "org.example.YourSuite",
suiteClassName = Some("org.example.YourSuite"),
testName = "say hey",
testText = "say hey")
val testSucceeded =
TestSucceeded(
new Ordinal(5),
suiteName = "org.example.YourSuite",
suiteId = "org.example.YourSuite",
suiteClassName = Some("org.example.YourSuite"),
testName = "say hey",
testText = "say hey",
recordedEvents = Vector.empty[RecordableEvent])
val testStarting3 =
TestStarting(
new Ordinal(6),
suiteName = "org.example.NevermindSuite",
suiteId = "org.example.NevermindSuite",
suiteClassName = Some("org.example.NevermindSuite"),
testName = "None",
testText = "say nevermind")
// testName is set to "None" here to verify proper encoding/decoding
// by Memento when name might be confused for an Option
val testCanceled =
TestCanceled(
new Ordinal(7),
message = "nevermind",
suiteName = "org.example.NevermindSuite",
suiteId = "org.example.NevermindSuite",
suiteClassName = Some("org.example.NevermindSuite"),
testName = "None",
testText = "say nevermind",
recordedEvents = Vector.empty[RecordableEvent],
rerunner = Some("org.example.NevermindSuite"))
val testStarting4 =
TestStarting(
new Ordinal(8),
suiteName = "org.example.BailSuite",
suiteId = "org.example.BailSuite",
suiteClassName = Some("org.example.BailSuite"),
testName = "say bail",
testText = "say bail")
val suiteAborted =
SuiteAborted(
new Ordinal(9),
message = "bail",
suiteName = "org.example.BailSuite",
suiteId = "org.example.BailSuite",
suiteClassName = Some("org.example.BailSuite"),
rerunner = Some("org.example.BailSuite"))
test("""|MemoryReporter writes empty file upon RunComplete
|event if no failure events were reported""".stripMargin) {
val file = new File(OutputFileName)
file.delete
val reporter = new MemoryReporter(OutputFileName)
reporter(runStarting)
reporter(testStarting2)
reporter(testSucceeded)
reporter(runComplete)
assert(file.exists)
assert(file.length === 0)
file.delete
}
test("MemoryReporter records a failure event") {
val file = new File(OutputFileName)
file.delete
val reporter = new MemoryReporter(OutputFileName)
reporter(runStarting)
reporter(testStarting1)
reporter(testFailed)
reporter(testStarting2)
reporter(testSucceeded)
reporter(runComplete)
assert(file.exists)
assert(file.length !== 0)
val mementos = Memento.readFromFile(OutputFileName)
assert(mementos.length === 1)
val suiteParam = mementos(0).toSuiteParam
assert(suiteParam.className === testFailed.suiteClassName.get)
assert(suiteParam.testNames.length === 1)
assert(suiteParam.testNames(0) === testFailed.testName)
assert(suiteParam.wildcardTestNames.length === 0)
assert(suiteParam.nestedSuites.length === 0)
file.delete
}
test("MemoryReporter records multiple events") {
val file = new File(OutputFileName)
file.delete
val reporter = new MemoryReporter(OutputFileName)
reporter(runStarting)
reporter(testStarting1)
reporter(testFailed)
reporter(testStarting2)
reporter(testSucceeded)
reporter(testStarting3)
reporter(testCanceled)
reporter(testStarting4)
reporter(suiteAborted)
reporter(runComplete)
assert(file.exists)
assert(file.length !== 0)
val mementos = Memento.readFromFile(OutputFileName)
assert(mementos.length === 3)
val suiteParam0 = mementos(0).toSuiteParam
assert(suiteParam0.className === suiteAborted.suiteClassName.get)
assert(suiteParam0.testNames.length === 0)
assert(suiteParam0.wildcardTestNames.length === 0)
assert(suiteParam0.nestedSuites.length === 0)
val suiteParam1 = mementos(1).toSuiteParam
assert(suiteParam1.className === testCanceled.suiteClassName.get)
assert(suiteParam1.testNames.length === 1)
assert(suiteParam1.testNames(0) === testCanceled.testName)
assert(suiteParam1.wildcardTestNames.length === 0)
assert(suiteParam1.nestedSuites.length === 0)
val suiteParam2 = mementos(2).toSuiteParam
assert(suiteParam2.className === testFailed.suiteClassName.get)
assert(suiteParam2.testNames.length === 1)
assert(suiteParam2.testNames(0) === testFailed.testName)
assert(suiteParam2.wildcardTestNames.length === 0)
assert(suiteParam2.nestedSuites.length === 0)
file.delete
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/ShouldMessageSpec.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 SharedHelpers.thisLineNumber
import enablers.Messaging
import exceptions.TestFailedException
class ShouldMessageSpec extends Spec with Matchers {
def hadMessageInsteadOfExpectedMessage(left: Any, actualMessage: String, expectedMessage: String): String =
FailureMessages.hadMessageInsteadOfExpectedMessage(left, actualMessage, expectedMessage)
def hadMessage(left: Any, expectedMessage: String): String =
FailureMessages.hadExpectedMessage(left, expectedMessage)
def equaled(left: Any, right: Any): String =
FailureMessages.equaled(left, right)
def didNotEqual(left: Any, right: Any): String =
FailureMessages.didNotEqual(left, right)
def wasEqualTo(left: Any, right: Any): String =
FailureMessages.wasEqualTo(left, right)
def wasNotEqualTo(left: Any, right: Any): String =
FailureMessages.wasNotEqualTo(left, right)
object `The 'have message (xxx)' syntax` {
object `on Throwable` {
val t = new RuntimeException("We have an error!")
val t2 = new RuntimeException("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an empty-paren String message method` {
class Messenger(theMessage: String) {
def message(): String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an parameterless String message method` {
class Messenger(theMessage: String) {
def message: String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an parameterless String message val` {
class Messenger(theMessage: String) {
val message: String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an empty-paren String getMessage method` {
class Messenger(theMessage: String) {
def getMessage(): String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an parameterless String getMessage method` {
class Messenger(theMessage: String) {
def getMessage: String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
object `on an arbitrary object that has an parameterless String getMessage val` {
class Messenger(theMessage: String) {
val getMessage: String = theMessage
override def toString = "messenger"
}
val t = new Messenger("We have an error!")
val t2 = new Messenger("This is another error!")
def `should do nothing if message matches the throwable's message` {
t should have message "We have an error!"
}
def `should throw TFE with correct stack depth if message does not match the throwable's message` {
val e =intercept[TestFailedException] {
t should have message "We have a boom!"
}
e.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if message does not match the throwable's message and used with should not` {
t should not { have message "We have a boom!" }
t should not have message ("We have a boom!")
}
def `should throw TFE with correct stack depth if message matches throwable's message and used with should not` {
val e1 = intercept[TestFailedException] {
t should not { have message "We have an error!" }
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should not have message ("We have an error!")
}
e2.message should be (Some(hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-and expression` {
t should (have message ("We have an error!") and (equal (t)))
t should (equal (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and equal (t))
t should (equal (t) and have message ("We have an error!"))
t should (have message ("We have an error!") and (be (t)))
t should (be (t) and (have message ("We have an error!")))
t should (have message ("We have an error!") and be (t))
t should (be (t) and have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-and expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (equal (t)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (have message ("We have a boom!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and equal (t))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and have message ("We have a boom!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and (be (t)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (have message ("We have a boom!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") and be (t))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and have message ("We have a boom!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-and expression and not` {
t should (not have message ("We have a boom!") and (equal (t)))
t should (equal (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and equal (t))
t should (equal (t) and not have message ("We have a boom!"))
t should (not have message ("We have a boom!") and (be (t)))
t should (be (t) and (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") and be (t))
t should (be (t) and not have message ("We have a boom!"))
}
def `should do nothing if error message matches and used in a logical-and expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (equal (t)))
}
e1.message should be (Some(hadMessage(t, "We have an error!")))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t) and (not have message ("We have an error!")))
}
e2.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and equal (t))
}
e3.message should be (Some(hadMessage(t, "We have an error!")))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t) and not have message ("We have an error!"))
}
e4.message should be (Some(equaled(t, t) + ", but " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and (be (t)))
}
e5.message should be (Some(hadMessage(t, "We have an error!")))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t) and (not have message ("We have an error!")))
}
e6.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") and be (t))
}
e7.message should be (Some(hadMessage(t, "We have an error!")))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t) and not have message ("We have an error!"))
}
e8.message should be (Some(wasEqualTo(t, t) + ", but " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message matches and used in a logical-or expression` {
t should (have message ("We have an error!") or (equal (t)))
t should (equal (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t))
t should (equal (t) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t)))
t should (be (t) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t))
t should (be (t) or have message ("We have an error!"))
t should (have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or equal (t))
t should (equal (t) or have message ("We have a boom!"))
t should (have message ("We have a boom!") or (be (t)))
t should (be (t) or (have message ("We have a boom!")))
t should (have message ("We have a boom!") or be (t))
t should (be (t) or have message ("We have a boom!"))
t should (have message ("We have an error!") or (equal (t2)))
t should (equal (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or equal (t2))
t should (equal (t2) or have message ("We have an error!"))
t should (have message ("We have an error!") or (be (t2)))
t should (be (t2) or (have message ("We have an error!")))
t should (have message ("We have an error!") or be (t2))
t should (be (t2) or have message ("We have an error!"))
}
def `should throw TFE with correct stack depth if error message does not match and used in a logical-or expression` {
val e1 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (equal (t2)))
}
e1.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (have message ("We have a boom!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or equal (t2))
}
e3.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or have message ("We have a boom!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or (be (t2)))
}
e5.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (have message ("We have a boom!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (have message ("We have a boom!") or be (t2))
}
e7.message should be (Some(hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or have message ("We have a boom!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessageInsteadOfExpectedMessage(t, "We have an error!", "We have a boom!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
def `should do nothing if error message does not match and used in a logical-or expression and not` {
t should (not have message ("We have a boom!") or (equal (t)))
t should (equal (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t))
t should (equal (t) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t)))
t should (be (t) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t))
t should (be (t) or not have message ("We have a boom!"))
t should (not have message ("We have an error!") or (equal (t)))
t should (equal (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or equal (t))
t should (equal (t) or not have message ("We have an error!"))
t should (not have message ("We have an error!") or (be (t)))
t should (be (t) or (not have message ("We have an error!")))
t should (not have message ("We have an error!") or be (t))
t should (be (t) or not have message ("We have an error!"))
t should (not have message ("We have a boom!") or (equal (t2)))
t should (equal (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or equal (t2))
t should (equal (t2) or not have message ("We have a boom!"))
t should (not have message ("We have a boom!") or (be (t2)))
t should (be (t2) or (not have message ("We have a boom!")))
t should (not have message ("We have a boom!") or be (t2))
t should (be (t2) or not have message ("We have a boom!"))
}
def `should throw TFE with correct stack depth if error message matches and used in a logical-or expression and not` {
val e1 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (equal (t2)))
}
e1.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e1.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e1.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e2 = intercept[TestFailedException] {
t should (equal (t2) or (not have message ("We have an error!")))
}
e2.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e2.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e2.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e3 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or equal (t2))
}
e3.message should be (Some(hadMessage(t, "We have an error!") + ", and " + didNotEqual(t, t2)))
e3.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e3.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e4 = intercept[TestFailedException] {
t should (equal (t2) or not have message ("We have an error!"))
}
e4.message should be (Some(didNotEqual(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e4.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e4.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e5 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or (be (t2)))
}
e5.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e5.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e5.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e6 = intercept[TestFailedException] {
t should (be (t2) or (not have message ("We have an error!")))
}
e6.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e6.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e6.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e7 = intercept[TestFailedException] {
t should (not have message ("We have an error!") or be (t2))
}
e7.message should be (Some(hadMessage(t, "We have an error!") + ", and " + wasNotEqualTo(t, t2)))
e7.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e7.failedCodeLineNumber should be (Some(thisLineNumber - 4))
val e8 = intercept[TestFailedException] {
t should (be (t2) or not have message ("We have an error!"))
}
e8.message should be (Some(wasNotEqualTo(t, t2) + ", and " + hadMessage(t, "We have an error!")))
e8.failedCodeFileName should be (Some("ShouldMessageSpec.scala"))
e8.failedCodeLineNumber should be (Some(thisLineNumber - 4))
}
}
}
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/Accumulation.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.Success
import scala.util.Failure
import scala.util.control.NonFatal
import scala.collection.GenTraversableOnce
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable.Builder
import scala.collection.GenSet
import Accumulation.Combinable
import Accumulation.Validatable
import Accumulation.TravValidatable
import Accumulation.Accumulatable
/**
* Provides mechanisms that enable errors to be accumulated in “accumulating <a href="Or.html"><code>Or</code></a>s,” <code>Or</code>s whose
* <a href="Bad.html"><code>Bad</code></a> type is an <a href="Every.html"><code>Every</code></a>.
*
* <p>
* The mechanisms are:
* </p>
*
* <ul>
* <li>Passing accumulating <code>Or</code>s to <code>withGood</code> methods</li>
* <li>Invoking <code>combined</code> on a container of accumulating <code>Or</code>s</li>
* <li>Invoking <code>validatedBy</code> on a container of any type, passing in a function from that type to an accumulating <code>Or</code></li>
* <li>Invoking <code>zip</code> on an accumulating <code>Or</code></li>
* <li>Invoking <code>when</code> on an accumulating <code>Or</code></li>
* </ul>
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*/
trait Accumulation {
import scala.language.{higherKinds, implicitConversions}
/**
* Implicitly converts an accumulating <code>Or</code> to an instance of <a href="Accumulation$$Acumulatable.html"><code>Accumulatable</code></a>, which
* enables <code>zip</code> and <code>when</code> methods to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingZip">Using <code>zip</code></a> and <a href="Or.html#usingWhen">Using <code>when</code></a>
* sections of the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertOrToAccumulatable[G, ERR, EVERY[b] <: Every[b]](accumulatable: G Or EVERY[ERR]): Accumulatable[G, ERR, EVERY] =
new Accumulatable[G, ERR, EVERY] {
def zip[H, OTHERERR >: ERR, OTHEREVERY[c] <: Every[c]](other: H Or OTHEREVERY[OTHERERR]): (G, H) Or Every[OTHERERR] = {
accumulatable match {
case Good(g) =>
other match {
case Good(h) => Good((g, h))
case Bad(otherB) => Bad(otherB)
}
case Bad(myBad) =>
other match {
case Good(_) => Bad(myBad)
case Bad(otherB) => Bad(myBad ++ otherB)
}
}
}
def when[OTHERERR >: ERR](validations: (G => Validation[OTHERERR])*): G Or Every[OTHERERR] = {
accumulatable match {
case Good(g) =>
val results = validations flatMap (_(g) match { case Fail(x) => Seq(x); case Pass => Seq.empty})
results.length match {
case 0 => Good(g)
case 1 => Bad(One(results.head))
case _ =>
val first = results.head
val tail = results.tail
val second = tail.head
val rest = tail.tail
Bad(Many(first, second, rest: _*))
}
case Bad(myBad) => Bad(myBad)
}
}
}
/**
* Implicitly converts a <em>covariant</em> <code>GenTraversableOnce</code> containing accumulating <code>Or</code>s to an instance of
* <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which
* enables the <code>combined</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section of the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertGenTraversableOnceToCombinable[G, ERR, EVERY[b] <: Every[b], TRAVONCE[+e] <: GenTraversableOnce[e]](xs: TRAVONCE[G Or EVERY[ERR]])(implicit cbf: CanBuildFrom[TRAVONCE[G Or EVERY[ERR]], G, TRAVONCE[G]]): Combinable[G, ERR, TRAVONCE] =
new Combinable[G, ERR, TRAVONCE] {
def combined: TRAVONCE[G] Or Every[ERR] = {
// So now I have an empty builder
val emptyTRAVONCEOfGBuilder: Builder[G, TRAVONCE[G]] = cbf(xs)
// So now I want to foldLeft across my TRAVONCE[G Or EVERY[ERR]], starting with an empty TRAVONCEOfGBuilder, and each step along the way, I'll
// += into the builder, what? Oh I get it. The result type of my foldLeft needs to be Builder[Seq[G]] Or Every[ERR]
val tempOr: Builder[G, TRAVONCE[G]] Or Every[ERR] =
xs.foldLeft((Good(emptyTRAVONCEOfGBuilder): Builder[G, TRAVONCE[G]] Or Every[ERR])) { (accumulator: Builder[G, TRAVONCE[G]] Or Every[ERR], nextElem: G Or Every[ERR]) =>
(accumulator, nextElem) match {
case (Good(bldr), Good(ele)) => Good(bldr += ele)
case (Good(_), Bad(err)) => Bad(err)
case (Bad(errA), Bad(errB)) => Bad(errA ++ errB)
case (Bad(errA), Good(_)) => Bad(errA)
}
}
tempOr map (_.result)
}
}
/**
* Implicitly converts a <em>covariant</em> <code>GenTraversableOnce</code> containing accumulating <code>Or</code>s whose inferred <code>Good</code> type
* is inferred as <code>Nothing</code> to an instance of
* <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which
* enables the <code>combined</code> method to be invoked on it.
*/
implicit def convertGenTraversableOnceToCombinableNothing[ERR, EVERY[b] <: Every[b], TRAVONCE[+e] <: GenTraversableOnce[e]](xs: TRAVONCE[Nothing Or EVERY[ERR]])(implicit cbf: CanBuildFrom[TRAVONCE[Nothing Or EVERY[ERR]], Nothing, TRAVONCE[Nothing]]): Combinable[Nothing, ERR, TRAVONCE] = convertGenTraversableOnceToCombinable[Nothing, ERR, EVERY, TRAVONCE](xs)(cbf)
// Must have another one for Sets, because they are not covariant. Will need to handle Good/Nothing case specially therefore, and plan to do that
// with another implicit here. Or just don't support Nothing.
/**
* Implicitly converts a <code>Set</code> containing accumulating <code>Or</code>s to an instance of <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which
* enables the <code>combined</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section of the main documentation for class <code>Or</code>.
* </p>
*
* <p>
* Note: This implicit is required for <code>Set</code>s because although <code>Set</code>s are <code>GenTraversableOnce</code>s, they aren't covariant, so
* the implicit conversion provided by <code>convertGenTraversableOnceToCombinable</code> will not be applied, because it only works on <em>covariant</em>
* <code>GenTraversableOnce</code>s.
* </p>
*/
implicit def convertGenSetToCombinable[G, ERR, X, EVERY[b] <: Every[b], SET[e] <: GenSet[e]](xs: SET[X with (G Or EVERY[ERR])])(implicit cbf: CanBuildFrom[SET[X with (G Or EVERY[ERR])], G, SET[G]]): Combinable[G, ERR, SET] =
new Combinable[G, ERR, SET] {
def combined: SET[G] Or Every[ERR] = {
// So now I have an empty builder
val emptySETOfGBuilder: Builder[G, SET[G]] = cbf(xs)
// So now I want to foldLeft across my SET[G Or EVERY[ERR]], starting with an empty SETOfGBuilder, and each step along the way, I'll
// += into the builder, what? Oh I get it. The result type of my foldLeft needs to be Builder[Seq[G]] Or Every[ERR]
val tempOr: Builder[G, SET[G]] Or Every[ERR] =
xs.foldLeft((Good(emptySETOfGBuilder): Builder[G, SET[G]] Or Every[ERR])) { (accumulator: Builder[G, SET[G]] Or Every[ERR], nextElem: G Or Every[ERR]) =>
(accumulator, nextElem) match {
case (Good(bldr), Good(ele)) => Good(bldr += ele)
case (Good(_), Bad(err)) => Bad(err)
case (Bad(errA), Bad(errB)) => Bad(errA ++ errB)
case (Bad(errA), Good(_)) => Bad(errA)
}
}
tempOr map (_.result)
}
}
/**
* Implicitly converts a <code>Set</code> containing accumulating <code>Or</code>s whose <code>Good</code> type is inferred as <code>Nothing</code> to an
* instance of <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which
* enables the <code>combined</code> method to be invoked on it.
*
* <p>
* Note: This implicit is required for <code>Set</code>s because although <code>Set</code>s are <code>GenTraversableOnce</code>s, they aren't covariant, so
* the implicit conversion provided by <code>convertGenTraversableOnceToCombinableNothing</code> will not be applied, because it only works on <em>covariant</em>
* <code>GenTraversableOnce</code>s.
* </p>
*/
implicit def convertGenSetToCombinableNothing[ERR, X, EVERY[b] <: Every[b], SET[e] <: GenSet[e]](xs: SET[X with (Nothing Or EVERY[ERR])])(implicit cbf: CanBuildFrom[SET[X with (Nothing Or EVERY[ERR])], Nothing, SET[Nothing]]): Combinable[Nothing, ERR, SET] = convertGenSetToCombinable[Nothing, ERR, X, EVERY, SET](xs)(cbf)
/**
* Implicitly converts an <code>Every</code> containing accumulating <code>Or</code>s to an instance of
* <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which enables the <code>combined</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section of the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertEveryToCombinable[G, ERR](oneToMany: Every[G Or Every[ERR]]): Combinable[G, ERR, Every] =
new Combinable[G, ERR, Every] {
def combined: Every[G] Or Every[ERR] = {
val vec = oneToMany.toVector
val z: Every[G] Or Every[ERR] =
vec.head match {
case Good(g) => Good(One(g))
case Bad(err) => Bad(err)
}
vec.tail.foldLeft(z) { (accumulator: Every[G] Or Every[ERR], nextElem: G Or Every[ERR]) =>
(accumulator, nextElem) match {
case (Good(everyG), Good(g)) => Good(everyG :+ g)
case (Good(_), Bad(err)) => Bad(err)
case (Bad(errA), Bad(errB)) => Bad(errA ++ errB)
case (Bad(errA), Good(_)) => Bad(errA)
}
}
}
}
/**
* Implicitly converts an <code>Option</code> containing accumulating <code>Or</code>s to an instance of
* <a href="Accumulation$$Combinable.html"><code>Combinable</code></a>, which enables the <code>combined</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section of the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertOptionToCombinable[G, ERR](option: Option[G Or Every[ERR]]): Combinable[G, ERR, Option] =
new Combinable[G, ERR, Option] {
def combined: Option[G] Or Every[ERR] =
option match {
case Some(Good(g)) => Good(Some(g))
case Some(Bad(err)) => Bad(err)
case None => Good(None)
}
}
/**
* Implicitly converts a <code>GenTraversableOnce</code> to an instance of <code>Validatable</code>, which
* enables the <code>validatedBy</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertGenTraversableOnceToValidatable[G, TRAVONCE[e] <: GenTraversableOnce[e]](xs: TRAVONCE[G]): TravValidatable[G, TRAVONCE] =
new TravValidatable[G, TRAVONCE] {
def validatedBy[H, ERR, EVERY[e] <: Every[e]](fn: G => H Or EVERY[ERR])(implicit cbf: CanBuildFrom[TRAVONCE[G], H, TRAVONCE[H]]): TRAVONCE[H] Or Every[ERR] = {
// So now I have an empty builder
val emptyTRAVONCEOfGBuilder: Builder[H, TRAVONCE[H]] = cbf(xs)
// So now I want to foldLeft across my TRAVONCE[G Or EVERY[ERR]], starting with an empty TRAVONCEOfGBuilder, and each step along the way, I'll
// += into the builder, what? Oh I get it. The result type of my foldLeft needs to be Builder[Seq[G]] Or Every[ERR]
val tempOr: Builder[H, TRAVONCE[H]] Or Every[ERR] =
xs.foldLeft((Good(emptyTRAVONCEOfGBuilder): Builder[H, TRAVONCE[H]] Or Every[ERR])) { (accumulator: Builder[H, TRAVONCE[H]] Or Every[ERR], nextElem: G) =>
(accumulator, fn(nextElem)) match {
case (Good(bldr), Good(ele)) => Good(bldr += ele)
case (Good(bldr), Bad(err)) => Bad(err)
case (Bad(errA), Bad(errB)) => Bad(errA ++ errB)
case (Bad(errA), Good(ele)) => Bad(errA)
}
}
tempOr map (_.result)
}
}
/**
* Implicitly converts an <code>Every</code> to an instance of <code>Validatable</code>, which
* enables the <code>validatedBy</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertEveryToValidatable[G](oneToMany: Every[G]): Validatable[G, Every] =
new Validatable[G, Every] {
def validatedBy[H, ERR, EVERY[e] <: Every[e]](fn: G => H Or EVERY[ERR]): Every[H] Or Every[ERR] = {
val vec = oneToMany.toVector
val z: Every[H] Or Every[ERR] =
fn(vec.head) match {
case Good(h) => Good(One(h))
case Bad(err) => Bad(err)
}
vec.tail.foldLeft(z) { (accumulator: Every[H] Or Every[ERR], nextElem: G) =>
(accumulator, fn(nextElem)) match {
case (Good(everyG), Good(h)) => Good(everyG :+ h)
case (Good(_), Bad(err)) => Bad(err)
case (Bad(errA), Bad(errB)) => Bad(errA ++ errB)
case (Bad(errA), Good(_)) => Bad(errA)
}
}
}
}
/**
* Implicitly converts an <code>Option</code> to an instance of <code>Validatable</code>, which
* enables the <code>validatedBy</code> method to be invoked on it.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
implicit def convertOptionToValidatable[G](option: Option[G]): Validatable[G, Option] =
new Validatable[G, Option] {
def validatedBy[H, ERR, EVERY[e] <: Every[e]](fn: G => H Or EVERY[ERR]): Option[H] Or Every[ERR] = {
option.map(fn) match {
case Some(Good(h)) => Good(Some(h))
case Some(Bad(err)) => Bad(err)
case None => Good(None)
}
}
}
/**
* Given a <code>Good</code> accumulating <code>Or</code>, apply it to the given function and return the result, wrapped in a <code>Good</code>;
* else return the given <code>Bad</code>.
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*/
@deprecated("Please use map on Or instead")
def withGood[A, ERR, RESULT](
a: A Or Every[ERR]
)(
fn: A => RESULT
): RESULT Or Every[ERR] = {
a match {
case Good(valid) => Good(fn(valid))
case Bad(every) => Bad(every)
}
}
/**
* Given 2 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR]
)(
fn: (A, B) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b)(fn.curried)
private def withGoodCurried[A, B, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR]
)(
fn: A => B => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (B => RESULT) Or Every[ERR] = withGood[A, ERR, B => RESULT](a)(fn)
b match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 3 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR]
)(
fn: (A, B, C) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c)(fn.curried)
private def withGoodCurried[A, B, C, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR]
)(
fn: A => B => C => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (C => RESULT) Or Every[ERR] = withGoodCurried[A, B, ERR, C => RESULT](a, b)(fn)
c match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 4 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR]
)(
fn: (A, B, C, D) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d)(fn.curried)
private def withGoodCurried[A, B, C, D, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR]
)(
fn: A => B => C => D => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (D => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, ERR, D => RESULT](a, b, c)(fn)
d match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 5 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR]
)(
fn: (A, B, C, D, E) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e)(fn.curried)
private def withGoodCurried[A, B, C, D, E, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR]
)(
fn: A => B => C => D => E => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (E => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, ERR, E => RESULT](a, b, c, d)(fn)
e match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 6 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR]
)(
fn: (A, B, C, D, E, F) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR]
)(
fn: A => B => C => D => E => F => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (F => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, ERR, F => RESULT](a, b, c, d, e)(fn)
f match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 7 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (G => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, ERR, G => RESULT](a, b, c, d, e, f)(fn)
g match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 8 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (H => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, ERR, H => RESULT](a, b, c, d, e, f, g)(fn)
h match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 9 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (I => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, ERR, I => RESULT](a, b, c, d, e, f, g, h)(fn)
i match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 10 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (J => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, ERR, J => RESULT](a, b, c, d, e, f, g, h, i)(fn)
j match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 11 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (K => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, ERR, K => RESULT](a, b, c, d, e, f, g, h, i, j)(fn)
k match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 12 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (L => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, ERR, L => RESULT](a, b, c, d, e, f, g, h, i, j, k)(fn)
l match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 13 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (M => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, ERR, M => RESULT](a, b, c, d, e, f, g, h, i, j, k, l)(fn)
m match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 14 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (N => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, ERR, N => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m)(fn)
n match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 15 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (O => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, ERR, O => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n)(fn)
o match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 16 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (P => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, ERR, P => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)(fn)
p match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 17 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (Q => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, ERR, Q => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p)(fn)
q match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 18 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => R => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (R => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, ERR, R => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q)(fn)
r match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 19 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => R => S => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (S => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, ERR, S => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r)(fn)
s match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 20 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => R => S => T => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (T => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, ERR, T => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s)(fn)
t match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 21 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR],
u: U Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR],
u: U Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => R => S => T => U => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (U => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, ERR, U => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t)(fn)
u match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
/**
* Given 22 <code>Good</code> accumulating <code>Or</code>s, apply them to the given function and return the result, wrapped in a <code>Good</code>;
* else return a <code>Bad</code> containing every error (<em>i.e.</em>, a <code>Bad</code> whose <code>Every</code> includes every value that
* appears in any <code>Bad</code>s passed to <code>withGood</code>).
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*
* @return a <code>Good</code> result, if all passed <code>Or</code>s were <code>Good</code>; else a <code>Bad</code> containing every error.
*/
def withGood[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR],
u: U Or Every[ERR],
v: V Or Every[ERR]
)(
fn: (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V) => RESULT
): RESULT Or Every[ERR] = withGoodCurried(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v)(fn.curried)
private def withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, ERR, RESULT](
a: A Or Every[ERR],
b: B Or Every[ERR],
c: C Or Every[ERR],
d: D Or Every[ERR],
e: E Or Every[ERR],
f: F Or Every[ERR],
g: G Or Every[ERR],
h: H Or Every[ERR],
i: I Or Every[ERR],
j: J Or Every[ERR],
k: K Or Every[ERR],
l: L Or Every[ERR],
m: M Or Every[ERR],
n: N Or Every[ERR],
o: O Or Every[ERR],
p: P Or Every[ERR],
q: Q Or Every[ERR],
r: R Or Every[ERR],
s: S Or Every[ERR],
t: T Or Every[ERR],
u: U Or Every[ERR],
v: V Or Every[ERR]
)(
fn: A => B => C => D => E => F => G => H => I => J => K => L => M => N => O => P => Q => R => S => T => U => V => RESULT
): RESULT Or Every[ERR] = {
val funOrError: (V => RESULT) Or Every[ERR] = withGoodCurried[A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, ERR, V => RESULT](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u)(fn)
v match {
case Good(valid) =>
funOrError match {
case Good(validFun) => Good(validFun(valid))
case Bad(every) => Bad(every)
}
case Bad(every) =>
funOrError match {
case Good(_) => Bad(every)
case Bad(funEvery) => Bad(funEvery ++ every)
}
}
}
}
/**
* Companion object to trait <code>Accumulation</code> that allows <code>Accumulation</code>'s members to be imported
* rather than mixed in, and also contains nested traits used by implicit conversions declared in
* trait <code>Accumulations</code>.
*
* <p>
* For more information and examples, see the <a href="Or.html#accumulatingErrors">Accumulating errors with <code>Or</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*/
object Accumulation extends Accumulation {
import scala.language.higherKinds
/**
* Adds a <code>combined</code> method to “collections” of accumulating <code>Or</code>s via an implicit conversion provided by
* trait <a href="Accumulation.html"><code>Accumulation</code></a>.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*/
trait Combinable[G, ERR, COLL[_]] {
/**
* Combines a collection <code>COLL</code> of <code>Or</code>s of type <code>G</code> <code>Or</code> <code>EVERY[ERR]</code> (where <code>EVERY</code>
* is some subtype of <code>Every</code>) into a single <code>Or</code> of
* type <code>COLL[G]</code> <code>Or</code> <code>Every[ERR]</code>.
*
* <p>
* Note: this process implemented by this method is sometimes called a “sequence.”
* </p>
*
* <p>
* For more information and examples, see the <a href="Or.html#usingCombined">Using <code>combined</code></a> section
* of the main documentation for class <code>Or</code>.
* </p>
*/
def combined: COLL[G] Or Every[ERR]
}
/**
* Adds a <code>validatedBy</code> method to (non-<code>GenTraversableOnce</code>) “collections” via an implicit conversion provided by
* trait <a href="Accumulation.html"><code>Accumulation</code></a>.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
trait Validatable[G, COLL[_]] {
/**
* Maps a collection <code>COLL</code> of <code>G</code>s into <code>Or</code>s of type <code>H</code> <code>Or</code> <code>EVERY[ERR]</code> (where <code>EVERY</code>
* is some subtype of <code>Every</code>) using the passed function <code>fn</code>, then combines the resulting <code>Or</code>s into a single <code>Or</code> of
* type <code>COLL[H]</code> <code>Or</code> <code>Every[ERR]</code>.
*
* <p>
* Note: this process implemented by this method is sometimes called a “traverse.”
* </p>
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
def validatedBy[H, ERR, EVERY[e] <: Every[e]](fn: G => H Or EVERY[ERR]): COLL[H] Or Every[ERR]
}
/**
* Adds a <code>validatedBy</code> method to <code>GenTraversableOnce</code> via an implicit conversion provided by
* trait <a href="Accumulation.html"><code>Accumulation</code></a>.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
trait TravValidatable[G, TRAVONCE[e] <: GenTraversableOnce[e]] {
/**
* Maps a <code>GenTraversableOnce</code> of <code>G</code>s into <code>Or</code>s of type <code>H</code> <code>Or</code> <code>EVERY[ERR]</code> (where <code>EVERY</code>
* is some subtype of <code>Every</code>) using the passed function <code>fn</code>, then combines the resulting <code>Or</code>s into a single <code>Or</code> of
* type <code>COLL[H]</code> <code>Or</code> <code>Every[ERR]</code>.
*
* <p>
* Note: this process implemented by this method is sometimes called a “traverse.”
* </p>
*
* <p>
* For more information and examples, see the <a href="Or.html#usingValidatedBy">Using <code>validatedBy</code></a> section of
* the main documentation for class <code>Or</code>.
* </p>
*/
def validatedBy[H, ERR, EVERY[e] <: Every[e]](fn: G => H Or EVERY[ERR])(implicit cbf: CanBuildFrom[TRAVONCE[G], H, TRAVONCE[H]]): TRAVONCE[H] Or Every[ERR]
}
/**
* Adds <code>zip</code> and <code>when</code> methods to <a href="Or.html"><code>Or</code></a>s vai an implicit conversion provided by
* trait <a href="Accumulation.html"><code>Accumulation</code></a>.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingZip">Using <code>zip</code></a> and <a href="Or.html#usingWhen">Using <code>when</code></a>
* sections of the main documentation for class <code>Or</code>.
* </p>
*/
trait Accumulatable[G, ERR, EVERY[b] <: Every[b]] {
/**
* Zips two accumulating <code>Or</code>s together into a <code>Good</code> pair (<code>Tuple2[G, H]</code>) if both <code>Or</code>s are
* <code>Good</code>, else a <code>Bad</code> containing every error.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingZip">Using <code>zip</code></a>
* section of the main documentation for class <code>Or</code>.
* </p>
*/
def zip[H, OTHERERR >: ERR, OTHEREVERY[c] <: Every[c]](other: H Or OTHEREVERY[OTHERERR]): (G, H) Or Every[OTHERERR]
/**
* Given a <code>Good</code> accumulating <code>Or</code>, applies the given validation functions to the <code>Good</code> value and returns
* either the same <code>Good</code>, if all validations resulted in <code>Pass</code>, else returns a <code>Bad</code> containing every
* error reported by validation <code>Fail</code> results; Given a <code>Bad</code> accumualting <code>Or</code>, returns the same <code>Bad</code>.
*
* <p>
* For more information and examples, see the <a href="Or.html#usingWhen">Using <code>when</code></a>
* section of the main documentation for class <code>Or</code>.
* </p>
*/
def when[OTHERERR >: ERR](validations: (G => Validation[OTHERERR])*): G Or Every[OTHERERR]
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/exceptions/ModifiableMessage.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.exceptions
/**
* Trait implemented by exception types that can modify their detail message.
*
* <p>
* This trait facilitates the <code>withClue</code> construct provided by trait
* <a href="../Assertions.html"><code>Assertions</code></a>. This construct enables extra information (or "clues") to
* be included in the detail message of a thrown exception. Although both
* <code>assert</code> and <code>expect</code> provide a way for a clue to be
* included directly, <code>intercept</code> and ScalaTest matcher expressions
* do not. Here's an example of clues provided directly in <code>assert</code>:
* </p>
*
* <pre class="stHighlight">
* assert(1 + 1 === 3, "this is a clue")
* </pre>
*
* <p>
* and in <code>expect</code>:
* </p>
*
* <pre class="stHighlight">
* expect(3, "this is a clue") { 1 + 1 }
* </pre>
*
* <p>
* The exceptions thrown by the previous two statements will include the clue
* string, <code>"this is a clue"</code>, in the exceptions detail message.
* To get the same clue in the detail message of an exception thrown
* by a failed <code>intercept</code> call requires using <code>withClue</code>:
* </p>
*
* <pre class="stHighlight">
* withClue("this is a clue") {
* intercept[IndexOutOfBoundsException] {
* "hi".charAt(-1)
* }
* }
* </pre>
*
* <p>
* Similarly, to get a clue in the exception resulting from an exception arising out
* of a ScalaTest matcher expression, you need to use <code>withClue</code>. Here's
* an example:
* </p>
*
* <pre class="stHighlight">
* withClue("this is a clue") {
* 1 + 1 should === (3)
* }
* </pre>
*
* <p>
* Exception types that mix in this trait have a <code>modifyMessage</code> method, which
* returns an exception identical to itself, except with the detail message option replaced with
* the result of invoking the passed function, supplying the current detail message option
* as the lone <code>String</code> parameter.
* </p>
*/
trait ModifiableMessage[T <: Throwable] { this: Throwable =>
/**
* Returns an instance of this exception's class, identical to this exception,
* except with the detail message option replaced with
* the result of invoking the passed function, <code>fun</code>, supplying the current detail message option
* as the lone <code>Option[String]</code> parameter.
*
* <p>
* Implementations of this method may either mutate this exception or return
* a new instance with the revised detail message.
* </p>
*
* @param fun A function that returns the new detail message option given the old one.
*/
def modifyMessage(fun: Option[String] => Option[String]): T
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/ExamplePropSpec.scala | <filename>scalatest-test.js/src/test/scala/test/ExamplePropSpec.scala
package test
import org.scalatest.PropSpec
class ExamplePropSpec extends PropSpec {
property("an empty Set should have size 0") {
assert(Set.empty[Int].size == 0)
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/fixture/AsyncFixtures.scala | <filename>scalatest/src/main/scala/org/scalatest/fixture/AsyncFixtures.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.scalatest.fixture
import org.scalatest.OutcomeOf._
import org.scalatest._
import exceptions.StackDepthExceptionHelper._
import scala.concurrent.{ExecutionContext, Future}
trait AsyncFixtures extends SuiteMixin { this: Suite with TestRegistration =>
final override def withFixture(test: NoArgTest): Outcome = {
throw new exceptions.NotAllowedException(FailureMessages.withFixtureNotAllowedInAsyncFixtures, getStackDepthFun("AsyncFixtures.scala", "withFixture"))
}
final override def withFixture(test: OneArgTest): Outcome = {
throw new exceptions.NotAllowedException(FailureMessages.withFixtureNotAllowedInAsyncFixtures, getStackDepthFun("AsyncFixtures.scala", "withFixture"))
}
/**
* A test function taking no arguments and returning an <code>Future[Outcome]</code>.
*
* <p>
* For more detail and examples, see the relevant section in the
* <a href="FlatSpec.html#withFixtureNoArgTest">documentation for trait <code>fixture.FlatSpec</code></a>.
* </p>
*/
trait OneArgAsyncTest extends ((FixtureParam) => Future[Outcome]) with TestData {
/**
* Runs the body of the test, returning an <code>Future[Outcome]</code>.
*/
def apply(fixture: FixtureParam): Future[Outcome]
}
def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome]
} |
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/enablers/EvidenceThat.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.EqualityConstraint
import org.scalactic.Equality
import scala.collection.GenTraversable
import scala.language.implicitConversions
import scala.language.higherKinds
final class EvidenceThat[R] {
abstract class CanEqual[L] {
def areEqual(leftSide: L, rightSide: R): Boolean
}
def canEqualByConstraint[L](implicit constraint: EqualityConstraint[L, R]): CanEqual[L] =
new CanEqual[L] {
def areEqual(leftSide: L, rightSide: R): Boolean = constraint.areEqual(leftSide, rightSide)
}
def canEqualByEquality[L](equality: Equality[L]): CanEqual[L] =
new CanEqual[L] {
def areEqual(leftSide: L, rightSide: R): Boolean = equality.areEqual(leftSide, rightSide)
}
abstract class CanBeContainedIn[L] {
def contains(leftSide: L, rightSide: R): Boolean
def containsOneOf(container: L, elements: scala.collection.Seq[R]): Boolean
def containsNoneOf(container: L, elements: scala.collection.Seq[R]): Boolean
}
def canBeContainedIn[L](constraint: ContainingConstraint[L, R]): CanBeContainedIn[L] =
new CanBeContainedIn[L] {
def contains(container: L, ele: R): Boolean = constraint.contains(container, ele)
def containsOneOf(container: L, elements: scala.collection.Seq[R]): Boolean = constraint.containsOneOf(container, elements)
def containsNoneOf(container: L, elements: scala.collection.Seq[R]): Boolean = constraint.containsNoneOf(container, elements)
}
abstract class CanBeContainedInAggregation[L] {
def containsAtLeastOneOf(aggregation: L, eles: Seq[R]): Boolean
def containsTheSameElementsAs(leftAggregation: L, rightAggregation: GenTraversable[R]): Boolean
def containsOnly(aggregation: L, eles: Seq[R]): Boolean
def containsAllOf(aggregation: L, eles: Seq[R]): Boolean
def containsAtMostOneOf(aggregation: L, eles: Seq[R]): Boolean
}
def canBeContainedInAggregation[L](constraint: AggregatingConstraint[L, R]): CanBeContainedInAggregation[L] =
new CanBeContainedInAggregation[L] {
def containsAtLeastOneOf(aggregation: L, eles: Seq[R]): Boolean = constraint.containsAtLeastOneOf(aggregation, eles)
def containsTheSameElementsAs(leftAggregation: L, rightAggregation: GenTraversable[R]): Boolean = constraint.containsTheSameElementsAs(leftAggregation, rightAggregation)
def containsOnly(aggregation: L, eles: Seq[R]): Boolean = constraint.containsOnly(aggregation, eles)
def containsAllOf(aggregation: L, eles: Seq[R]): Boolean = constraint.containsAllOf(aggregation, eles)
def containsAtMostOneOf(aggregation: L, eles: Seq[R]): Boolean = constraint.containsAtMostOneOf(aggregation, eles)
}
abstract class CanBeContainedInSequence[L] {
def containsInOrder(sequence: L, eles: Seq[R]): Boolean
def containsInOrderOnly(sequence: L, eles: Seq[R]): Boolean
def containsTheSameElementsInOrderAs(leftSequence: L, rightSequence: GenTraversable[R]): Boolean
}
def canBeContainedInSequence[L](constraint: SequencingConstraint[L, R]): CanBeContainedInSequence[L] =
new CanBeContainedInSequence[L] {
def containsInOrder(sequence: L, eles: Seq[R]): Boolean = constraint.containsInOrder(sequence, eles)
def containsInOrderOnly(sequence: L, eles: Seq[R]): Boolean = constraint.containsInOrderOnly(sequence, eles)
def containsTheSameElementsInOrderAs(leftSequence: L, rightSequence: GenTraversable[R]): Boolean = constraint.containsTheSameElementsInOrderAs(leftSequence, rightSequence)
}
}
object EvidenceThat {
implicit def constrainedEquality[L, R](implicit constraint: EqualityConstraint[L, R]): EvidenceThat[R]#CanEqual[L] =
(new EvidenceThat[R]).canEqualByConstraint[L]
implicit def convertEqualityToEvidenceThatRCanEqualL[L, R](equality: Equality[L])(implicit constraint: EqualityConstraint[L, R]): EvidenceThat[R]#CanEqual[L] =
(new EvidenceThat[R]).canEqualByEquality[L](equality)
implicit def constrainedContaining[L, R](implicit constraint: ContainingConstraint[L, R]): EvidenceThat[R]#CanBeContainedIn[L] =
(new EvidenceThat[R]).canBeContainedIn[L](constraint)
implicit def convertEqualityToEvidenceThatRCanBeContainedInL[L, R](equality: Equality[R])(implicit cvt: Equality[R] => ContainingConstraint[L, R]): EvidenceThat[R]#CanBeContainedIn[L] =
(new EvidenceThat[R]).canBeContainedIn[L](cvt(equality))
// Converts an explicitly given Equality[Entry] to the required EvidenceThat...
implicit def enableScalaTestEntryContaining[K, V, JMAP[k, v] <: java.util.Map[k, v]](equality: Equality[java.util.Map.Entry[K, V]]): EvidenceThat[org.scalactic.Entry[K, V]]#CanBeContainedIn[JMAP[K, V]] = {
(new EvidenceThat[org.scalactic.Entry[K, V]]).canBeContainedIn[JMAP[K, V]] {
// Here I need a ContainingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]]
new ContainingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]] {
import scala.collection.JavaConverters._
def contains(map: JMAP[K, V], ele: org.scalactic.Entry[K, V]): Boolean = {
map.entrySet.asScala.exists((e: java.util.Map.Entry[K, V]) => equality.areEqual(e, ele))
}
private val constraint: EqualityConstraint[java.util.Map.Entry[K, V], org.scalactic.Entry[K, V]] = new org.scalactic.EqualityPolicy.BasicEqualityConstraint(equality)
def containsOneOf(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
val foundSet = ContainingConstraint.checkOneOf[java.util.Map.Entry[K, V], org.scalactic.Entry[K, V]](map.entrySet.asScala, elements, constraint)
foundSet.size == 1
}
def containsNoneOf(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
val found = ContainingConstraint.checkNoneOf[java.util.Map.Entry[K, V], org.scalactic.Entry[K, V]](map.entrySet.asScala, elements, constraint)
!found.isDefined
}
}
}
}
implicit def constrainedAggregating[L, R](implicit constraint: AggregatingConstraint[L, R]): EvidenceThat[R]#CanBeContainedInAggregation[L] =
(new EvidenceThat[R]).canBeContainedInAggregation[L](constraint)
implicit def convertEqualityToEvidenceThatRCanBeContainedInAggregationL[L, R](equality: Equality[R])(implicit cvt: Equality[R] => AggregatingConstraint[L, R]): EvidenceThat[R]#CanBeContainedInAggregation[L] =
(new EvidenceThat[R]).canBeContainedInAggregation[L](cvt(equality))
// Converts an explicitly given Equality[Entry] to the required EvidenceThat...
implicit def enableScalaTestEntryAggregating[K, V, JMAP[k, v] <: java.util.Map[k, v]](equality: Equality[java.util.Map.Entry[K, V]]): EvidenceThat[org.scalactic.Entry[K, V]]#CanBeContainedInAggregation[JMAP[K, V]] = {
(new EvidenceThat[org.scalactic.Entry[K, V]]).canBeContainedInAggregation[JMAP[K, V]] {
// Here I need an AggregatingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]]
new AggregatingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]] {
import scala.collection.JavaConverters._
private val constraint: EqualityConstraint[java.util.Map.Entry[K, V], org.scalactic.Entry[K, V]] = new org.scalactic.EqualityPolicy.BasicEqualityConstraint(equality)
def containsAtLeastOneOf(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
map.entrySet.asScala.exists((e: java.util.Map.Entry[K, V]) => elements.exists((ele: org.scalactic.Entry[K, V]) => constraint.areEqual(e, ele)))
}
def containsTheSameElementsAs(map: JMAP[K, V], elements: GenTraversable[org.scalactic.Entry[K, V]]): Boolean = {
AggregatingConstraint.checkTheSameElementsAs(map.entrySet.asScala, elements, constraint)
}
def containsOnly(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
AggregatingConstraint.checkOnly(map.entrySet.asScala, elements, constraint)
}
def containsAllOf(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
AggregatingConstraint.checkAllOf(map.entrySet.asScala, elements, constraint)
}
def containsAtMostOneOf(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
AggregatingConstraint.checkAtMostOneOf(map.entrySet.asScala, elements, constraint)
}
}
}
}
implicit def constrainedSequencing[L, R](implicit constraint: SequencingConstraint[L, R]): EvidenceThat[R]#CanBeContainedInSequence[L] =
(new EvidenceThat[R]).canBeContainedInSequence[L](constraint)
implicit def convertEqualityToEvidenceThatRCanBeContainedInSequenceL[L, R](equality: Equality[R])(implicit cvt: Equality[R] => SequencingConstraint[L, R]): EvidenceThat[R]#CanBeContainedInSequence[L] =
(new EvidenceThat[R]).canBeContainedInSequence[L](cvt(equality))
// Converts an explicitly given Equality[Entry] to the required EvidenceThat...
implicit def enableScalaTestEntrySequencing[K, V, JMAP[k, v] <: java.util.Map[k, v]](equality: Equality[java.util.Map.Entry[K, V]]): EvidenceThat[org.scalactic.Entry[K, V]]#CanBeContainedInSequence[JMAP[K, V]] = {
(new EvidenceThat[org.scalactic.Entry[K, V]]).canBeContainedInSequence[JMAP[K, V]] {
// Here I need an SequencingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]]
new SequencingConstraint[JMAP[K, V], org.scalactic.Entry[K, V]] {
import scala.collection.JavaConverters._
private val constraint: EqualityConstraint[java.util.Map.Entry[K, V], org.scalactic.Entry[K, V]] = new org.scalactic.EqualityPolicy.BasicEqualityConstraint(equality)
def containsInOrder(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
SequencingConstraint.checkInOrder(map.entrySet.iterator.asScala.toVector, elements, constraint)
}
def containsInOrderOnly(map: JMAP[K, V], elements: scala.collection.Seq[org.scalactic.Entry[K, V]]): Boolean = {
SequencingConstraint.checkInOrderOnly(map.entrySet.iterator.asScala.toVector, elements, constraint)
}
def containsTheSameElementsInOrderAs(map: JMAP[K, V], elements: GenTraversable[org.scalactic.Entry[K, V]]): Boolean = {
SequencingConstraint.checkTheSameElementsInOrderAs(map.entrySet.iterator.asScala.toVector, elements, constraint)
}
}
}
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/JSuite.scala | <filename>scalatest/src/main/scala/org/scalatest/JSuite.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 Suite.getSimpleNameOfAnObjectsClass
// Scala version o fwhat I'm thinking JSuite might have in Java
private[scalatest] trait JSuite { thisSuite =>
/**
* Runs this suite of tests.
*
* @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
*
* @throws NullPointerException if any passed parameter is <code>null</code>.
*/
def runJSuite(testName: Option[String], args: Args): Status // Will be testName: nullable String, args: JArgs
/**
* A <code>Set</code> of test names. If this <code>Suite</code> contains no tests, this method returns an empty <code>Set</code>.
*
* <p>
* Although subclass and subtrait implementations of this method may return a <code>Set</code> whose iterator produces <code>String</code>
* test names in a well-defined order, the contract of this method does not required a defined order. Subclasses are free to
* implement this method and return test names in either a defined or undefined order.
* </p>
*/
def getTestNames(): java.util.Set[String]
/**
* A <code>Map</code> whose keys are <code>String</code> tag names with which tests in this <code>Suite</code> are marked, and
* whose values are the <code>Set</code> of test names marked with each tag. If this <code>Suite</code> contains no tags, this
* method returns an empty <code>Map</code>.
*
* <p>
* Subclasses may implement this method to define and/or discover tags in a custom manner, but overriding method implementations
* should never return an empty <code>Set</code> as a value. If a tag has no tests, its name should not appear as a key in the
* returned <code>Map</code>.
* </p>
*/
def getTags(): java.util.Map[String, java.util.Set[String]]
/**
* The total number of tests that are expected to run when this <code>Suite</code>'s <code>run</code> method is invoked.
*
* @param filter a <code>Filter</code> with which to filter tests to count based on their tags
*/
def getExpectedTestCount(filter: Filter): Int // Will be JFilter
/**
* The fully qualified name of the class that can be used to rerun this suite.
*/
def getRerunner: Option[String] // Will return a nullable String
/**
* This suite's style name.
*
* <p>
* This lifecycle method provides a string that is used to determine whether this suite object's
* style is one of the <a href="tools/Runner$.html#specifyingChosenStyles">chosen styles</a> for
* the project.
* </p>
*/
def getStyleName(): String // Actually, not sure we need this over in the JSuite area Maybe this will just not exist over there.
// But it might make it simpler to be consistent.
/**
* A user-friendly suite name for this <code>Suite</code>.
*
* <p>
* This trait's
* implementation of this method returns the simple name of this object's class. This
* trait's implementation of <code>runNestedSuites</code> calls this method to obtain a
* name for <code>Report</code>s to pass to the <code>suiteStarting</code>, <code>suiteCompleted</code>,
* and <code>suiteAborted</code> methods of the <code>Reporter</code>.
* </p>
*
* @return this <code>Suite</code> object's suite name.
*/
def getSuiteName(): String = getSimpleNameOfAnObjectsClass(thisSuite)
/**
* A string ID for this <code>Suite</code> that is intended to be unique among all suites reported during a run.
*
* <p>
* This trait's
* implementation of this method returns the fully qualified name of this object's class.
* Each suite reported during a run will commonly be an instance of a different <code>Suite</code> class,
* and in such cases, this default implementation of this method will suffice. However, in special cases
* you may need to override this method to ensure it is unique for each reported suite. For example, if you write
* a <code>Suite</code> subclass that reads in a file whose name is passed to its constructor and dynamically
* creates a suite of tests based on the information in that file, you will likely need to override this method
* in your <code>Suite</code> subclass, perhaps by appending the pathname of the file to the fully qualified class name.
* That way if you run a suite of tests based on a directory full of these files, you'll have unique suite IDs for
* each reported suite.
* </p>
*
* <p>
* The suite ID is <em>intended</em> to be unique, because ScalaTest does not enforce that it is unique. If it is not
* unique, then you may not be able to uniquely identify a particular test of a particular suite. This ability is used,
* for example, to dynamically tag tests as having failed in the previous run when rerunning only failed tests.
* </p>
*
* @return this <code>Suite</code> object's ID.
*/
def getSuiteId(): String = thisSuite.getClass.getName
}
|
cquiroz/scalatest | scalactic/src/main/scala/org/scalactic/MapEqualityConstraints.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 EqualityPolicy._
/**
* Provides an implicit method that loosens the equality constraint defined by <code>TypeCheckedTripleEquals</code> or <code>ConversionCheckedTripleEquals</code>
* for Scala <code>Map</code>s to one that more closely matches Scala's approach to <code>Map</code> equality.
*
* <p>
* Scala's approach to <code>Map</code> equality is that if both objects being compared are <code>Map</code>s, the elements are compared to determine equality.
* This means you could compare an immutable <code>TreeMap</code> and a mutable <code>HashMap</code> for equality, for instance, and get true so long as the two maps
* contained the same key-value mappings. Here's an example:
* </p>
*
* <pre class="stREPL">
* scala> import scala.collection.immutable.TreeMap
* import scala.collection.immutable.TreeMap
*
* scala> import scala.collection.mutable.HashMap
* import scala.collection.mutable.HashMap
*
* scala> TreeMap("one" -> 1, "two" -> 2) == HashMap("one" -> 1, "two" -> 2)
* res0: Boolean = true
* </pre>
*
* <p>
* Such a comparison would not, however, compile if you used <code>===</code> under either <code>TypeCheckedTripleEquals</code> or <code>ConversionCheckedTripleEquals</code>,
* because <code>TreeMap</code> and <code>HashMap</code> are not in a subtype/supertype relationship, nor does an implicit conversion by default exist between them:
* </p>
*
* <pre class="stREPL">
* scala> import org.scalactic._
* import org.scalactic._
*
* scala> import TypeCheckedTripleEquals._
* import TypeCheckedTripleEquals._
*
* scala> TreeMap("one" -> 1, "two" -> 2) === HashMap("one" -> 1, "two" -> 2)
* <console>:16: error: types scala.collection.immutable.TreeMap[String,Int] and
* scala.collection.mutable.HashMap[String,Int] do not adhere to the equality constraint selected for
* the === and !== operators; the missing implicit parameter is of type
* org.scalactic.EqualityConstraint[scala.collection.immutable.TreeMap[String,Int],
* scala.collection.mutable.HashMap[String,Int]]
* TreeMap("one" -> 1, "two" -> 2) === HashMap("one" -> 1, "two" -> 2)
* ^
* </pre>
*
* <p>
* If you mix or import the implicit conversion provided by <code>MapEqualityConstraint</code>, however, the comparison will be allowed:
* </p>
*
* <pre class="stREPL">
* scala> import MapEqualityConstraints._
* import MapEqualityConstraints._
*
* scala> TreeMap("one" -> 1, "two" -> 2) === HashMap("one" -> 1, "two" -> 2)
* res2: Boolean = true
* </pre>
*
* <p>
* The equality constraint provided by this trait requires that both left and right sides are subclasses of <code>scala.collection.GenMap</code> and that
* an <code>EqualityConstraint</code> can be found for both key types and both value types. In the example above, both the <code>TreeMap</code> and
* <code>HashMap</code> are subclasses of <code>scala.collection.GenMap</code>, and the regular <code>TypeCheckedTripleEquals</code> provides equality
* constraints for the key types, both of which are <code>String</code>, and value types, both of which are <code>Int</code>. By contrast, this
* trait would not allow a <code>TreeMap[String, Int]</code> to be compared against a <code>HashMap[String, java.util.Date]</code>, because no equality constraint
* will exist between the value types <code>Int</code> and <code>Date</code>:
* </p>
*
* <pre class="stREPL">
* scala> import java.util.Date
* import java.util.Date
*
* scala> TreeMap("one" -> 1, "two" -> 2) === HashMap("one" -> new Date, "two" -> new Date)
* <console>:20: error: types scala.collection.immutable.TreeMap[String,Int] and
* scala.collection.mutable.HashMap[String,java.util.Date] do not adhere to the equality constraint selected for
* the === and !== operators; the missing implicit parameter is of type
* org.scalactic.EqualityConstraint[scala.collection.immutable.TreeMap[String,Int],
* scala.collection.mutable.HashMap[String,java.util.Date]]
* TreeMap("one" -> 1, "two" -> 2) === HashMap("one" -> new Date, "two" -> new Date)
* ^
* </pre>
*
* @author <NAME>
*/
trait MapEqualityConstraints {
import scala.language.higherKinds
/**
* Provides an equality constraint that allows two subtypes of <code>scala.collection.GenMap</code>s to be compared for equality with <code>===</code> so long
* as an <code>EqualityConstraint</code> is available for both key types and both value types.
*/
implicit def mapEqualityConstraint[KA, VA, CA[ka, kb] <: collection.GenMap[ka, kb], KB, VB, CB[kb, vb] <: collection.GenMap[kb, vb]](implicit equalityOfA: Equality[CA[KA, VA]], evKey: Constraint[KA, KB], evValue: Constraint[VA, VB]): Constraint[CA[KA, VA], CB[KB, VB]] = new BasicConstraint[CA[KA, VA], CB[KB, VB]](equalityOfA)
}
/**
* Companion object that facilitates the importing of <code>MapEqualityConstraints</code> members as
* an alternative to mixing it in. One use case is to import <code>MapEqualityConstraints</code> members so you can use
* them in the Scala interpreter.
*/
object MapEqualityConstraints extends MapEqualityConstraints
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/StreamlinedXmlNormMethods.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 annotation.tailrec
import scala.xml.{Elem,Node,NodeSeq}
import org.scalactic.{NormMethods, Uniformity}
/**
* Subtrait of <a href="../scalactic/NormMethods.html"><code>NormMethods</code></a> that provides
* an implicit <code>Uniformity[T]</code> for subtypes of <code>scala.xml.NodeSeq</code> that enables
* you to streamline XML by invoking <code>.norm</code> on it.
*
* <p>
* Here's an example:
* </p>
*
* <pre class="stREPL">
* scala> <good><day>sunshine</day></good> == <good>
* | <day>
* | sunshine
* | </day>
* | </good>
* res1: Boolean = false
*
* scala> import org.scalactic._
* import org.scalactic._
*
* scala> import TripleEquals._
* import TripleEquals._
*
* scala> import org.scalatest.StreamlinedXmlNormMethods._
* import org.scalatest.StreamlinedXmlNormMethods._
*
* scala> <good><day>sunshine</day></good> === <good>
* | <day>
* | sunshine
* | </day>
* | </good>.norm
* res2: Boolean = true
* </pre>
*/
trait StreamlinedXmlNormMethods extends StreamlinedXml with NormMethods {
/**
* Provides an implicit <a href="../scalactic/Uniformity.html"><code>Uniformity[T]</code></a>
* instance for any subtype of <code>scala.xml.NodeSeq</code> that will normalize the XML by removing empty text nodes and trimming
* non-empty text nodes.
*
* <p>
* This <code>Uniformity[T]</code> enables normalization of XML by invoking the <code>.norm</code>
* method on subtypes of <code>scala.xml.NodeSeq</code>. See the main documentation for this trait for more
* details and examples.
* </p>
*
* @return a <code>Uniformity[T]</code> instance that normalizes XML for testing
*/
implicit override def streamlined[T <: NodeSeq]: Uniformity[T] = super.streamlined[T]
}
/**
* Companion object that facilitates the importing of <code>StreamlinedXmlNormMethods</code> members as
* an alternative to mixing it the trait. One use case is to import <code>StreamlinedXmlNormMethods</code>'s implicit so you can use
* it in the Scala interpreter.
*
* @author <NAME>
*/
object StreamlinedXmlNormMethods extends StreamlinedXmlNormMethods
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/matchers/TypeMatcherMacro.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.matchers
import scala.reflect.macros.Context
import org.scalatest.words.{ResultOfAnTypeInvocation, MatcherWords, ResultOfATypeInvocation}
import org.scalatest.{UnquotedString, Resources, Suite, FailureMessages, Assertions}
import org.scalactic.Prettifier
private[scalatest] object TypeMatcherMacro {
// Check that no type parameter is specified, if any does, give a friendly compiler warning.
def checkTypeParameter(context: Context)(tree: context.Tree, methodName: String) {
import context.universe._
tree match {
case Apply(
TypeApply(
Select(
_,
methodNameTermName
),
typeList: List[TypeTree]
),
_
) if methodNameTermName.decoded == methodName =>
// Got a type list, let's go through it
typeList.foreach { t =>
t.original match {
case AppliedTypeTree(tpt, args) => // type is specified, let's give warning.
context.warning(args(0).pos, "Type parameter should not be specified because it will be erased at runtime, please use _ instead. Note that in future version of ScalaTest this will give a compiler error.")
case _ => // otherwise don't do anything
}
}
case _ => // otherwise don't do anything
}
}
// Do checking on type parameter and generate AST that create a 'a type' matcher
def aTypeMatcherImpl(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
val tree = aType.tree
// check type parameter
checkTypeParameter(context)(tree, "a")
/**
* Generate AST that does the following code:
*
* org.scalatest.matchers.TypeMatcherHelper.aTypeMatcher(aType)
*/
context.Expr(
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("aTypeMatcher")
),
List(tree)
)
)
}
// Do checking on type parameter and generate AST that create a 'an type' matcher
def anTypeMatcherImpl(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
val tree = anType.tree
// check type parameter
checkTypeParameter(context)(tree, "an")
/**
* Generate AST that does the following code:
*
* org.scalatest.matchers.TypeMatcherHelper.anTypeMatcher(anType)
*/
context.Expr(
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("anTypeMatcher")
),
List(tree)
)
)
}
// Do checking on type parameter and generate AST that create a negated 'a type' matcher
def notATypeMatcher(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
val tree = aType.tree
// check type parameter
checkTypeParameter(context)(tree, "a")
/**
* Generate AST that does the following code:
*
* org.scalatest.matchers.TypeMatcherHelper.notATypeMatcher(aType)
*/
context.Expr(
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("notATypeMatcher")
),
List(tree)
)
)
}
// Do checking on type parameter and generate AST that create a negated 'an type' matcher
def notAnTypeMatcher(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
val tree = anType.tree
// check type parameter
checkTypeParameter(context)(tree, "an")
/**
* Generate AST that does the following code:
*
* org.scalatest.matchers.TypeMatcherHelper.notAnTypeMatcher(anType)
*/
context.Expr(
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("notAnTypeMatcher")
),
List(tree)
)
)
}
// Do checking on type parameter and generate AST that does a 'and not' logical expression matcher for 'a type' matcher.
def andNotATypeMatcher(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
// create a negated matcher from notATypeMatcher
val rhs: context.Expr[Matcher[Any]] = notATypeMatcher(context)(aType)
/**
* Generate AST for code that call the 'and' method on the Matcher instance (reference through 'owner'):
*
* owner.and(rhs)
*/
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
context.Expr(
Apply(
Select(
Select(
qualifier,
"owner"
),
newTermName("and")
),
List(rhs.tree)
)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with 'and not' syntax only.")
}
}
// Do checking on type parameter and generate AST that does a 'and not' logical expression matcher for 'an type' matcher.
def andNotAnTypeMatcher(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
// create a negated matcher from notAnTypeMatcher
val rhs: context.Expr[Matcher[Any]] = notAnTypeMatcher(context)(anType)
/**
* Generate AST for code that call the 'and' method on the Matcher instance (reference through 'owner'):
*
* owner.and(rhs)
*/
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
context.Expr(
Apply(
Select(
Select(
qualifier,
"owner"
),
newTermName("and")
),
List(rhs.tree)
)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with 'and not' syntax only.")
}
}
// Do checking on type parameter and generate AST that does a 'or not' logical expression matcher for 'a type' matcher.
def orNotATypeMatcher(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
// create a negated matcher from notATypeMatcher
val rhs: context.Expr[Matcher[Any]] = notATypeMatcher(context)(aType)
/**
* Generate AST for code that call the 'or' method on the Matcher instance (reference through 'owner'):
*
* owner.or(rhs)
*/
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
context.Expr(
Apply(
Select(
Select(
qualifier,
"owner"
),
newTermName("or")
),
List(rhs.tree)
)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with 'or not' syntax only.")
}
}
// Do checking on type parameter and generate AST that does a 'or not' logical expression matcher for 'an type' matcher.
def orNotAnTypeMatcher(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Matcher[Any]] = {
import context.universe._
// create a negated matcher from notAnTypeMatcher
val rhs: context.Expr[Matcher[Any]] = notAnTypeMatcher(context)(anType)
/**
* Generate AST for code that call the 'or' method on the Matcher instance (reference through 'owner'):
*
* owner.or(rhs)
*/
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
context.Expr(
Apply(
Select(
Select(
qualifier,
"owner"
),
newTermName("or")
),
List(rhs.tree)
)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with 'or not' syntax only.")
}
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkAType, used by 'shouldBe a [type]' syntax
def shouldBeATypeImpl(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = aType.tree
// check type parameter
checkTypeParameter(context)(tree, "a")
/**
* Generate AST to call TypeMatcherHelper.checkAType:
*
* org.scalatest.matchers.TypeMatcherHelper.checkAType(lhs, aType)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkAType")
),
List(Select(qualifier, newTermName("leftSideValue")), tree)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with shouldBe a [Type] syntax only.")
}
context.Expr(callHelper)
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkAType, used by 'mustBe a [type]' syntax
def mustBeATypeImpl(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = aType.tree
// check type parameter
checkTypeParameter(context)(tree, "a")
/**
* Generate AST to call TypeMatcherHelper.checkAType:
*
* org.scalatest.matchers.TypeMatcherHelper.checkAType(lhs, aType)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkAType")
),
List(Select(qualifier, newTermName("leftSideValue")), tree)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with mustBe a [Type] syntax only.")
}
context.Expr(callHelper)
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkAType, used by 'shouldBe an [type]' syntax
def shouldBeAnTypeImpl(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = anType.tree
// check type parameter
checkTypeParameter(context)(tree, "an")
/**
* Generate AST to call TypeMatcherHelper.checkAnType:
*
* org.scalatest.matchers.TypeMatcherHelper.checkAnType(lhs, anType)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkAnType")
),
List(Select(qualifier, newTermName("leftSideValue")), tree)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with shouldBe an [Type] syntax only.")
}
context.Expr(callHelper)
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkAnType, used by 'mustBe an [type]' syntax
def mustBeAnTypeImpl(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = anType.tree
// check type parameter
checkTypeParameter(context)(tree, "an")
/**
* Generate AST to call TypeMatcherHelper.checkAnType:
*
* org.scalatest.matchers.TypeMatcherHelper.checkAnType(lhs, anType)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkAnType")
),
List(Select(qualifier, newTermName("leftSideValue")), tree)
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with mustBe an [Type] syntax only.")
}
context.Expr(callHelper)
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkATypeShouldBeTrue
def checkATypeShouldBeTrueImpl(context: Context)(aType: context.Expr[ResultOfATypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = aType.tree
// check type parameter
checkTypeParameter(context)(tree, "a")
/**
* Generate AST to call TypeMatcherHelper.checkATypeShouldBeTrue:
*
* org.scalatest.matchers.TypeMatcherHelper.checkATypeShouldBeTrue(lhs, aType, shouldBeTrue)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkATypeShouldBeTrue")
),
List(Select(qualifier, newTermName("left")), tree, Select(qualifier, newTermName("shouldBeTrue")))
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with should not be a [Type] syntax only.")
}
context.Expr(callHelper)
}
// Do checking on type parameter and generate AST to call TypeMatcherHelper.checkAnTypeShouldBeTrue
def checkAnTypeShouldBeTrueImpl(context: Context)(anType: context.Expr[ResultOfAnTypeInvocation[_]]): context.Expr[Unit] = {
import context.universe._
val tree = anType.tree
// check type parameter
checkTypeParameter(context)(tree, "an")
/**
* Generate AST to call TypeMatcherHelper.checkAnTypeShouldBeTrue:
*
* org.scalatest.matchers.TypeMatcherHelper.checkAnTypeShouldBeTrue(lhs, anType, shouldBeTrue)
*/
val callHelper =
context.macroApplication match {
case Apply(Select(qualifier, _), _) =>
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("org")),
newTermName("scalatest")
),
newTermName("matchers")
),
newTermName("TypeMatcherHelper")
),
newTermName("checkAnTypeShouldBeTrue")
),
List(Select(qualifier, newTermName("left")), tree, Select(qualifier, newTermName("shouldBeTrue")))
)
case _ => context.abort(context.macroApplication.pos, "This macro should be used with should not be an [Type] syntax only.")
}
context.Expr(callHelper)
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/matchers/BePropertyMatcherSpec.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 BePropertyMatcherSpec extends Spec {
object `BePropertyMatcherMatcher ` {
object `instance created by BePropertyMatcher apply method` {
val bePropertyMatcher = BePropertyMatcher[File] { file =>
BePropertyMatchResult(true, "test")
}
def `should have pretty toString` {
bePropertyMatcher.toString should be ("BePropertyMatcher[java.io.File](java.io.File => BePropertyMatchResult)")
}
}
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/matchers/MatchResult.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.matchers
import org.scalactic.Prettifier
import org.scalatest.Resources
/**
* The result of a match operation, such as one performed by a <a href="Matcher.html"><code>Matcher</code></a> or
* <a href="BeMatcher.html"><code>BeMatcher</code></a>, which
* contains one field that indicates whether the match succeeded, four fields that provide
* raw failure messages to report under different circumstances, four fields providing
* arguments used to construct the final failure messages using raw failure messages
* and a <a href="../../Prettifier.html"><code>Prettifier</code></a>. Using the default constructor,
* failure messages will be constructed lazily (when required).
*
* <p>
* A <code>MatchResult</code>'s <code>matches</code> field indicates whether a match succeeded. If it succeeded,
* <code>matches</code> will be <code>true</code>.
* There are four methods, <code>failureMessage</code>, <code>negatedfailureMessage</code>, <code>midSentenceFailureMessage</code>
* and <code>negatedMidSentenceFailureMessage</code> that can be called to get final failure message strings, one of which will be
* presented to the user in case of a match failure. If a match succeeds, none of these strings will be used, because no failure
* message will be reported (<em>i.e.</em>, because there was no failure to report). If a match fails (<code>matches</code> is <code>false</code>),
* the <code>failureMessage</code> (or <code>midSentenceFailure</code>—more on that below) will be reported to help the user understand what went wrong.
* </p>
*
* <h2>Understanding <code>negatedFailureMessage</code></h2>
*
* <p>
* The <code>negatedFailureMessage</code> exists so that it can become the <code>failureMessage</code> if the matcher is <em>inverted</em>,
* which happens, for instance, if it is passed to <code>not</code>. Here's an example:
* </p>
*
* <pre class="stHighlight">
* val equalSeven = equal (7)
* val notEqualSeven = not (equalSeven)
* </pre>
*
* <p>
* The <code>Matcher[Int]</code> that results from passing 7 to <code>equal</code>, which is assigned to the <code>equalSeven</code>
* variable, will compare <code>Int</code>s passed to its
* <code>apply</code> method with 7. If 7 is passed, the <code>equalSeven</code> match will succeed. If anything other than 7 is passed, it
* will fail. By contrast, the <code>notEqualSeven</code> matcher, which results from passing <code>equalSeven</code> to <code>not</code>, does
* just the opposite. If 7 is passed, the <code>notEqualSeven</code> match will fail. If anything other than 7 is passed, it will succeed.
* </p>
*
* <p>
* For example, if 8 is passed, <code>equalSeven</code>'s <code>MatchResult</code> will contain:
* </p>
*
* <pre class="stExamples">
* expression: equalSeven(8)
* matches: false
* failureMessage: 8 did not equal 7
* negatedFailureMessage: 8 equaled 7
* </pre>
*
* <p>
* Although the <code>negatedFailureMessage</code> is nonsensical, it will not be reported to the user. Only the <code>failureMessage</code>,
* which does actually explain what caused the failure, will be reported by the user. If you pass 8 to <code>notEqualSeven</code>'s <code>apply</code>
* method, by contrast, the <code>failureMessage</code> and <code>negatedFailureMessage</code> will be:
* </p>
*
* <pre class="stExamples">
* expression: notEqualSeven(8)
* matches: true
* failureMessage: 8 equaled 7
* negatedFailureMessage: 8 did not equal 7
* </pre>
*
* <p>
* Note that the messages are swapped from the <code>equalSeven</code> messages. This swapping was effectively performed by the <code>not</code> matcher,
* which in addition to swapping the <code>failureMessage</code> and <code>negatedFailureMessage</code>, also inverted the
* <code>matches</code> value. Thus when you pass the same value to both <code>equalSeven</code> and <code>notEqualSeven</code> the <code>matches</code>
* field of one <code>MatchResult</code> will be <code>true</code> and the other <code>false</code>. Because the
* <code>matches</code> field of the <code>MatchResult</code> returned by <code>notEqualSeven(8)</code> is <code>true</code>,
* the nonsensical <code>failureMessage</code>, "<code>8 equaled 7</code>", will <em>not</em> be reported to the user.
* </p>
*
* <p>
* If 7 is passed, by contrast, the <code>failureMessage</code> and <code>negatedFailureMessage</code> of <code>equalSeven</code>
* will be:
* </p>
*
* <pre class="stExamples">
* expression: equalSeven(7)
* matches: true
* failureMessage: 7 did not equal 7
* negatedFailureMessage: 7 equaled 7
* </pre>
*
* <p>
* In this case <code>equalSeven</code>'s <code>failureMessage</code> is nonsensical, but because the match succeeded, the nonsensical message will
* not be reported to the user.
* If you pass 7 to <code>notEqualSeven</code>'s <code>apply</code>
* method, you'll get:
* </p>
*
* <pre class="stExamples">
* expression: notEqualSeven(7)
* matches: false
* failureMessage: 7 equaled 7
* negatedFailureMessage: 7 did not equal 7
* </pre>
*
* <p>
* Again the messages are swapped from the <code>equalSeven</code> messages, but this time, the <code>failureMessage</code> makes sense
* and explains what went wrong: the <code>notEqualSeven</code> match failed because the number passed did in fact equal 7. Since
* the match failed, this failure message, "<code>7 equaled 7</code>", will be reported to the user.
* </p>
*
* <h2>Understanding the "<code>midSentence</code>" messages</h2>
*
* <p>
* When a ScalaTest matcher expression that involves <code>and</code> or <code>or</code> fails, the failure message that
* results is composed from the failure messages of the left and right matcher operatnds to <code>and</code> or </code>or</code>.
* For example:
* </p>
*
* <pre class="stExamples">
* 8 should (equal (7) or equal (9))
* </pre>
*
* <p>
* This above expression would fail with the following failure message reported to the user:
* </p>
*
* <pre class="stExamples">
* 8 did not equal 7, and 8 did not equal 9
* </pre>
*
* <p>
* This works fine, but what if the failure messages being combined begin with a capital letter, such as:
* </p>
*
* <pre class="stExamples">
* The name property did not equal "Ricky"
* </pre>
*
* <p>
* A combination of two such failure messages might result in an abomination of English punctuation, such as:
* </p>
*
* <pre class="stExamples">
* The name property did not equal "Ricky", and The name property did not equal "Bobby"
* </pre>
*
* <p>
* Because ScalaTest is an internationalized application, taking all of its strings from a property file
* enabling it to be localized, it isn't a good idea to force the first character to lower case. Besides,
* it might actually represent a String value which should stay upper case. The <code>midSentenceFailureMessage</code>
* exists for this situation. If the failure message is used at the beginning of the sentence, <code>failureMessage</code>
* will be used. But if it appears mid-sentence, or at the end of the sentence, <code>midSentenceFailureMessage</code>
* will be used. Given these failure message strings:
* </p>
*
* <pre class="stExamples">
* failureMessage: The name property did not equal "Bobby"
* midSentenceFailureMessage: the name property did not equal "Bobby"
* </pre>
*
* <p>
* The resulting failure of the <code>or</code> expression involving to matchers would make any English teacher proud:
* </p>
*
* <pre class="stExamples">
* The name property did not equal "Ricky", and the name property did not equal "Bobby"
* </pre>
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param rawMidSentenceFailureMessage raw failure message suitable for appearing mid-sentence
* @param rawMidSentenceNegatedFailureMessage raw negated failure message suitable for appearing mid-sentence
* @param failureMessageArgs arguments for constructing failure message to report if a match fails
* @param negatedFailureMessageArgs arguments for constructing message with a meaning opposite to that of the failure message
* @param midSentenceFailureMessageArgs arguments for constructing failure message suitable for appearing mid-sentence
* @param midSentenceNegatedFailureMessageArgs arguments for constructing negated failure message suitable for appearing mid-sentence
* @param prettifier a <code>Prettifier</code> to prettify arguments before constructing the messages
*
* @author <NAME>
* @author <NAME>
*/
final case class MatchResult(
matches: Boolean,
rawFailureMessage: String,
rawNegatedFailureMessage: String,
rawMidSentenceFailureMessage: String,
rawMidSentenceNegatedFailureMessage: String,
failureMessageArgs: IndexedSeq[Any],
negatedFailureMessageArgs: IndexedSeq[Any],
midSentenceFailureMessageArgs: IndexedSeq[Any],
midSentenceNegatedFailureMessageArgs: IndexedSeq[Any],
prettifier: Prettifier = Prettifier.default
) {
/**
* Constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>rawFailureMessage</code>, and
* <code>rawNegativeFailureMessage</code> fields. The <code>rawMidSentenceFailureMessage</code> will return the same
* string as <code>rawFailureMessage</code>, and the <code>rawMidSentenceNegatedFailureMessage</code> will return the
* same string as <code>rawNegatedFailureMessage</code>. <code>failureMessageArgs</code>, <code>negatedFailureMessageArgs</code>,
* <code>midSentenceFailureMessageArgs</code>, <code>midSentenceNegatedFailureMessageArgs</code> will be <code>Vector.empty</code>
* and <code>Prettifier.default</code> will be used.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
*/
def this(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String) =
this(
matches,
rawFailureMessage,
rawNegatedFailureMessage,
rawFailureMessage,
rawNegatedFailureMessage,
Vector.empty,
Vector.empty,
Vector.empty,
Vector.empty,
Prettifier.default
)
/**
* Construct failure message to report if a match fails, using <code>rawFailureMessage</code>, <code>failureMessageArgs</code> and <code>prettifier</code>
*
* @return failure message to report if a match fails
*/
def failureMessage: String = if (failureMessageArgs.isEmpty) rawFailureMessage else makeString(rawFailureMessage, failureMessageArgs)
/**
* Construct message with a meaning opposite to that of the failure message, using <code>rawNegatedFailureMessage</code>, <code>negatedFailureMessageArgs</code> and <code>prettifier</code>
*
* @return message with a meaning opposite to that of the failure message
*/
def negatedFailureMessage: String = if (negatedFailureMessageArgs.isEmpty) rawNegatedFailureMessage else makeString(rawNegatedFailureMessage, negatedFailureMessageArgs)
/**
* Construct failure message suitable for appearing mid-sentence, using <code>rawMidSentenceFailureMessage</code>, <code>midSentenceFailureMessageArgs</code> and <code>prettifier</code>
*
* @return failure message suitable for appearing mid-sentence
*/
def midSentenceFailureMessage: String = if (midSentenceFailureMessageArgs.isEmpty) rawMidSentenceFailureMessage else makeString(rawMidSentenceFailureMessage, midSentenceFailureMessageArgs)
/**
* Construct negated failure message suitable for appearing mid-sentence, using <code>rawMidSentenceNegatedFailureMessage</code>, <code>midSentenceNegatedFailureMessageArgs</code> and <code>prettifier</code>
*
* @return negated failure message suitable for appearing mid-sentence
*/
def midSentenceNegatedFailureMessage: String = if (midSentenceNegatedFailureMessageArgs.isEmpty) rawMidSentenceNegatedFailureMessage else makeString(rawMidSentenceNegatedFailureMessage, midSentenceNegatedFailureMessageArgs)
/**
* Get a negated version of this MatchResult, matches field will be negated and all messages field will be substituted with its counter-part.
*
* @return a negated version of this MatchResult
*/
def negated: MatchResult = MatchResult(!matches, rawNegatedFailureMessage, rawFailureMessage, rawMidSentenceNegatedFailureMessage, rawMidSentenceFailureMessage, negatedFailureMessageArgs, failureMessageArgs, midSentenceNegatedFailureMessageArgs, midSentenceFailureMessageArgs)
private def makeString(rawString: String, args: IndexedSeq[Any]): String =
Resources.formatString(rawString, args.map(prettifier).toArray)
}
/**
* Companion object for the <code>MatchResult</code> case class.
*
* @author <NAME>
*/
object MatchResult {
/**
* Factory method that constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>failureMessage</code>,
* <code>negativeFailureMessage</code>, <code>midSentenceFailureMessage</code>,
* <code>midSentenceNegatedFailureMessage</code>, <code>failureMessageArgs</code>, and <code>negatedFailureMessageArgs</code> fields.
* <code>failureMessageArgs</code>, and <code>negatedFailureMessageArgs</code> will be used in place of <code>midSentenceFailureMessageArgs</code>
* and <code>midSentenceNegatedFailureMessageArgs</code>.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param rawMidSentenceFailureMessage raw failure message to report if a match fails
* @param rawMidSentenceNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param failureMessageArgs arguments for constructing failure message to report if a match fails
* @param negatedFailureMessageArgs arguments for constructing message with a meaning opposite to that of the failure message
* @return a <code>MatchResult</code> instance
*/
def apply(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String, rawMidSentenceFailureMessage: String,
rawMidSentenceNegatedFailureMessage: String, failureMessageArgs: IndexedSeq[Any], negatedFailureMessageArgs: IndexedSeq[Any]): MatchResult =
new MatchResult(matches, rawFailureMessage, rawNegatedFailureMessage, rawMidSentenceFailureMessage, rawMidSentenceNegatedFailureMessage, failureMessageArgs, negatedFailureMessageArgs, failureMessageArgs, negatedFailureMessageArgs, Prettifier.default)
/**
* Factory method that constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>rawFailureMessage</code>,
* <code>rawNegativeFailureMessage</code>, <code>rawMidSentenceFailureMessage</code>, and
* <code>rawMidSentenceNegatedFailureMessage</code> fields. All argument fields will have <code>Vector.empty</code> values.
* This is suitable to create MatchResult with eager error messages, and its mid-sentence messages need to be different.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param rawMidSentenceFailureMessage raw failure message to report if a match fails
* @param rawMidSentenceNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @return a <code>MatchResult</code> instance
*/
def apply(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String, rawMidSentenceFailureMessage: String,
rawMidSentenceNegatedFailureMessage: String): MatchResult =
new MatchResult(matches, rawFailureMessage, rawNegatedFailureMessage, rawMidSentenceFailureMessage, rawMidSentenceNegatedFailureMessage, Vector.empty, Vector.empty, Vector.empty, Vector.empty, Prettifier.default)
/**
* Factory method that constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>rawFailureMessage</code>, and
* <code>rawNegativeFailureMessage</code> fields. The <code>rawMidSentenceFailureMessage</code> will return the same
* string as <code>rawFailureMessage</code>, and the <code>rawMidSentenceNegatedFailureMessage</code> will return the
* same string as <code>rawNegatedFailureMessage</code>. All argument fields will have <code>Vector.empty</code> values.
* This is suitable to create MatchResult with eager error messages that have same mid-sentence messages.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @return a <code>MatchResult</code> instance
*/
def apply(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String): MatchResult =
new MatchResult(matches, rawFailureMessage, rawNegatedFailureMessage, rawFailureMessage, rawNegatedFailureMessage, Vector.empty, Vector.empty, Vector.empty, Vector.empty, Prettifier.default)
/**
* Factory method that constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>rawFailureMessage</code>,
* <code>rawNegativeFailureMessage</code> and <code>args</code> fields. The <code>rawMidSentenceFailureMessage</code> will return the same
* string as <code>rawFailureMessage</code>, and the <code>rawMidSentenceNegatedFailureMessage</code> will return the
* same string as <code>rawNegatedFailureMessage</code>. All argument fields will use <code>args</code> as arguments.
* This is suitable to create MatchResult with lazy error messages that have same mid-sentence messages and arguments.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param args arguments for error messages construction
* @return a <code>MatchResult</code> instance
*/
def apply(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String, args: IndexedSeq[Any]) =
new MatchResult(
matches,
rawFailureMessage,
rawNegatedFailureMessage,
rawFailureMessage,
rawNegatedFailureMessage,
args,
args,
args,
args,
Prettifier.default
)
/**
* Factory method that constructs a new <code>MatchResult</code> with passed <code>matches</code>, <code>rawFailureMessage</code>,
* <code>rawNegativeFailureMessage</code>, <code>failureMessageArgs</code> and <code>negatedFailureMessageArgs</code> fields.
* The <code>rawMidSentenceFailureMessage</code> will return the same string as <code>rawFailureMessage</code>, and the
* <code>rawMidSentenceNegatedFailureMessage</code> will return the same string as <code>rawNegatedFailureMessage</code>.
* The <code>midSentenceFailureMessageArgs</code> will return the same as <code>failureMessageArgs</code>, and the
* <code>midSentenceNegatedFailureMessageArgs</code> will return the same as <code>negatedFailureMessageArgs</code>.
* This is suitable to create MatchResult with lazy error messages that have same mid-sentence and use different arguments for
* negated messages.
*
* @param matches indicates whether or not the matcher matched
* @param rawFailureMessage raw failure message to report if a match fails
* @param rawNegatedFailureMessage raw message with a meaning opposite to that of the failure message
* @param failureMessageArgs arguments for constructing failure message to report if a match fails
* @param negatedFailureMessageArgs arguments for constructing message with a meaning opposite to that of the failure message
* @return a <code>MatchResult</code> instance
*/
def apply(matches: Boolean, rawFailureMessage: String, rawNegatedFailureMessage: String, failureMessageArgs: IndexedSeq[Any], negatedFailureMessageArgs: IndexedSeq[Any]) =
new MatchResult(
matches,
rawFailureMessage,
rawNegatedFailureMessage,
rawFailureMessage,
rawNegatedFailureMessage,
failureMessageArgs,
negatedFailureMessageArgs,
failureMessageArgs,
negatedFailureMessageArgs,
Prettifier.default
)
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/FactSpec.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 org.scalactic.PrettyMethods
import Fact._
class FactSpec extends FreeSpec with Matchers with PrettyMethods {
"A Fact" - {
val fact = No("1 did not equal 2", "1 equaled 2", "1 did not equal 2", "1 equaled 2")
"when negated" - {
"swaps failure and negated failure messages" in {
fact should equal (No("1 did not equal 2", "1 equaled 2", "1 did not equal 2", "1 equaled 2"))
!fact should equal (Yes("1 equaled 2", "1 did not equal 2", "1 equaled 2", "1 did not equal 2"))
val fact2 = Yes("{0} did not equal null", "The reference equaled null", "{0} did not equal null", "the reference equaled null", Vector("howdy"), Vector.empty)
fact2 should have (
'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),
'composite(false)
)
val fact2Negated = !fact2
fact2Negated should equal (No("The reference equaled null", "{0} did not equal null", "the reference equaled null", "{0} did not equal null", Vector.empty, Vector("howdy")))
fact2Negated should have (
'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")),
'composite(false)
)
}
"should maintain the same composite state" in {
!fact should have ('composite(false))
val factCopy = fact.copy(composite = true)
!factCopy should have ('composite(true))
}
}
"should construct localized strings from the raw strings and args" in {
val fact = No("{0} did not equal {1}", "{0} equaled {1}", "{0} did not equal {1}", "{0} equaled {1}", Vector(1, 2), Vector(1, 2))
fact should have (
'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)),
'composite(false)
)
}
"should use midSentenceFailureMessageArgs to construct midSentenceFailureMessage" in {
val fact = No("{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)
fact.midSentenceFailureMessage should be ("1 did not equal 2")
}
"should use midSentenceNegatedFailureMessageArgs to construct midSentenceNegatedFailureMessage" in {
val fact = No("{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))
fact.midSentenceNegatedFailureMessage should be ("1 equaled 2")
}
}
"The Fact companion objects factory methods" - {
"that takes two strings should work correctly" in {
val fact = Yes("one", "two")
fact should have (
'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),
'composite(false)
)
val ms = No("aaa", "bbb")
ms should have (
'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),
'composite(false)
)
}
"that takes four strings should work correctly" in {
val fact = Yes("one", "two", "three", "four")
fact should have (
'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),
'composite(false)
)
val ms = No("aaa", "bbb", "ccc", "ddd")
ms should have (
'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),
'composite(false)
)
}
"that takes four strings and two IndexedSeqs should work correctly" in {
val fact = Yes("one", "two", "three", "four", Vector(42), Vector(42.0))
fact should have (
'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)),
'composite(false)
)
val ms = No("aaa", "bbb", "ccc", "ddd", Vector("ho", "he"), Vector("foo", "fie"))
ms should have (
'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")),
'composite(false)
)
}
"that takes two strings and one IndexedSeq should work correctly" in {
val fact = Yes("one", "two", Vector(42))
fact should have (
'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)),
'composite(false)
)
val ms = No("aaa", "bbb", Vector("ho", "he"))
ms should have (
'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")),
'composite(false)
)
}
"that takes two strings and two IndexedSeqs should work correctly" in {
val fact = Yes("one", "two", Vector(42), Vector(42.0))
fact should have (
'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)),
'composite(false)
)
val ms = No("aaa", "bbb", Vector("ho", "he"), Vector("foo", "fie"))
ms should have (
'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")),
'composite(false)
)
}
"that takes four strings and four IndexedSeqs should work correctly" in {
val fact = Yes("one", "two", "three", "four", Vector(1), Vector(2), Vector(3), Vector(4))
fact should have (
'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)),
'composite(false)
)
val ms = No("aaa", "bbb", "ccc", "ddd", Vector('A'), Vector('B'), Vector('C'), Vector('D'))
ms should have (
'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')),
'composite(false)
)
}
"that takes four strings, four IndexedSeqs and composite should work correctly" in {
val fact = Yes("one", "two", "three", "four", Vector(1), Vector(2), Vector(3), Vector(4), true)
fact should have (
'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)),
'composite(true)
)
val ms = No("aaa", "bbb", "ccc", "ddd", Vector('A'), Vector('B'), Vector('C'), Vector('D'), true)
ms should have (
'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')),
'composite(true)
)
}
}
"The Fact obtained from and-ing two Facts" - {
"should be lazy about constructing strings" - {
"for No && No" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'))
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'))
val fact = leftSideNo && rightSideNo
fact shouldBe a [No]
fact.rawFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.failureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty))
fact.negatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty))
fact.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty))
fact.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty))
fact.failureMessageArgs should be (Vector('a', 'b'))
fact.negatedFailureMessageArgs should be (Vector('a', 'b'))
fact.composite should be (false)
}
"for No && Yes" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'))
val rightSideYes = Yes(Resources.rawWasNotLessThan, Resources.rawWasLessThan, Resources.rawWasNotLessThan, Resources.rawWasLessThan, Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'))
val fact = leftSideNo && rightSideYes
fact shouldBe a [No]
fact.rawFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.failureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty))
fact.negatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty))
fact.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty))
fact.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('a'.pretty, 'b'.pretty))
fact.failureMessageArgs should be (Vector('a', 'b'))
fact.negatedFailureMessageArgs should be (Vector('a', 'b'))
fact.composite should be (false)
}
"for Yes && No" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('c', 'b'),Vector('c', 'b'),Vector('c', 'b'),Vector('c', 'b'))
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('c', 'd'),Vector('c', 'd'),Vector('c', 'd'),Vector('c', 'd'))
val fact = leftSideYes && rightSideNo
fact shouldBe a [No]
fact.rawFailureMessage should be (Resources.rawCommaBut)
fact.rawNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawCommaBut)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.failureMessage should be (Resources.commaBut(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('c'.pretty, 'd'.pretty)))
fact.negatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasGreaterThan('c'.pretty, 'd'.pretty)))
fact.midSentenceFailureMessage should be (Resources.commaBut(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('c'.pretty, 'd'.pretty)))
fact.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('c'.pretty, 'b'.pretty), Resources.wasGreaterThan('c'.pretty, 'd'.pretty)))
fact.failureMessageArgs should be (Vector(NegatedFailureMessage(leftSideYes), MidSentenceFailureMessage(rightSideNo)))
fact.negatedFailureMessageArgs should be (Vector(NegatedFailureMessage(leftSideYes), MidSentenceNegatedFailureMessage(rightSideNo)))
fact.midSentenceFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(leftSideYes), MidSentenceFailureMessage(rightSideNo)))
fact.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(leftSideYes), MidSentenceNegatedFailureMessage(rightSideNo)))
fact.composite should be (true)
}
"for Yes && Yes" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'))
val rightSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'))
val fact = leftSideYes && rightSideYes
fact shouldBe a [Yes]
fact.rawFailureMessage should be (Resources.rawCommaBut)
fact.rawNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawCommaBut)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.failureMessage should be (Resources.commaBut(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('e'.pretty, 'd'.pretty)))
fact.negatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasGreaterThan('e'.pretty, 'd'.pretty)))
fact.midSentenceFailureMessage should be (Resources.commaBut(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('e'.pretty, 'd'.pretty)))
fact.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasGreaterThan('e'.pretty, 'b'.pretty), Resources.wasGreaterThan('e'.pretty, 'd'.pretty)))
fact.failureMessageArgs should be (Vector(NegatedFailureMessage(leftSideYes), MidSentenceFailureMessage(rightSideYes)))
fact.negatedFailureMessageArgs should be (Vector(NegatedFailureMessage(leftSideYes), MidSentenceNegatedFailureMessage(rightSideYes)))
fact.midSentenceFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(leftSideYes), MidSentenceFailureMessage(rightSideYes)))
fact.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceNegatedFailureMessage(leftSideYes), MidSentenceNegatedFailureMessage(rightSideYes)))
fact.composite should be (true)
}
}
"should be parenthesize composite facts" - {
"for non-composite && composite" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), false)
val rightSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), true)
val fact = leftSideYes && rightSideYes
fact.rawFailureMessage should be (Resources.rawRightParensCommaBut)
fact.rawNegatedFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawRightParensCommaBut)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.composite should be (true)
}
"for composite && non-composite" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), true)
val rightSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), false)
val fact = leftSideYes && rightSideYes
fact.rawFailureMessage should be (Resources.rawLeftParensCommaBut)
fact.rawNegatedFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawLeftParensCommaBut)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.composite should be (true)
}
"for composite && composite" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), true)
val rightSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), true)
val fact = leftSideYes && rightSideYes
fact.rawFailureMessage should be (Resources.rawBothParensCommaBut)
fact.rawNegatedFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawBothParensCommaBut)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.composite should be (true)
}
}
}
"The Fact obtained from or-ing two Facts" - {
"should be lazy about constructing strings" - {
"for No || No" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'))
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'))
val fact = leftSideNo || rightSideNo
fact shouldBe a [No]
fact.rawFailureMessage should be (Resources.rawCommaAnd)
fact.rawNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.failureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('a'.pretty, 'd'.pretty)))
fact.negatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasGreaterThan('a'.pretty, 'd'.pretty)))
fact.midSentenceFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotGreaterThan('a'.pretty, 'd'.pretty)))
fact.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasGreaterThan('a'.pretty, 'd'.pretty)))
fact.failureMessageArgs should be (Vector(FailureMessage(leftSideNo), MidSentenceFailureMessage(rightSideNo)))
fact.negatedFailureMessageArgs should be (Vector(FailureMessage(leftSideNo), MidSentenceNegatedFailureMessage(rightSideNo)))
fact.midSentenceFailureMessageArgs should be (Vector(MidSentenceFailureMessage(leftSideNo), MidSentenceFailureMessage(rightSideNo)))
fact.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceFailureMessage(leftSideNo), MidSentenceNegatedFailureMessage(rightSideNo)))
fact.composite should be (true)
}
"for No || Yes" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'),Vector('a', 'b'))
val rightSideYes = Yes(Resources.rawWasNotLessThan, Resources.rawWasLessThan, Resources.rawWasNotLessThan, Resources.rawWasLessThan, Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'),Vector('a', 'd'))
val fact = leftSideNo || rightSideYes
fact shouldBe a [Yes]
fact.rawFailureMessage should be (Resources.rawCommaAnd)
fact.rawNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawCommaAnd)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawCommaAnd)
fact.failureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotLessThan('a'.pretty, 'd'.pretty)))
fact.negatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasLessThan('a'.pretty, 'd'.pretty)))
fact.midSentenceFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasNotLessThan('a'.pretty, 'd'.pretty)))
fact.midSentenceNegatedFailureMessage should be (Resources.commaAnd(Resources.wasNotGreaterThan('a'.pretty, 'b'.pretty), Resources.wasLessThan('a'.pretty, 'd'.pretty)))
fact.failureMessageArgs should be (Vector(FailureMessage(leftSideNo), MidSentenceFailureMessage(rightSideYes)))
fact.negatedFailureMessageArgs should be (Vector(FailureMessage(leftSideNo), MidSentenceNegatedFailureMessage(rightSideYes)))
fact.midSentenceFailureMessageArgs should be (Vector(MidSentenceFailureMessage(leftSideNo), MidSentenceFailureMessage(rightSideYes)))
fact.midSentenceNegatedFailureMessageArgs should be (Vector(MidSentenceFailureMessage(leftSideNo), MidSentenceNegatedFailureMessage(rightSideYes)))
fact.composite should be (true)
}
"for Yes || No" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('c', 'b'),Vector('c', 'b'),Vector('c', 'b'),Vector('c', 'b'))
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('c', 'd'),Vector('c', 'd'),Vector('c', 'd'),Vector('c', 'd'))
val fact = leftSideYes || rightSideNo
fact shouldBe a [Yes]
fact.rawFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.failureMessage should be (Resources.wasNotGreaterThan('c'.pretty, 'b'.pretty))
fact.negatedFailureMessage should be (Resources.wasGreaterThan('c'.pretty, 'b'.pretty))
fact.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('c'.pretty, 'b'.pretty))
fact.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('c'.pretty, 'b'.pretty))
fact.failureMessageArgs should be (Vector('c', 'b'))
fact.negatedFailureMessageArgs should be (Vector('c', 'b'))
fact.composite should be (false)
}
"for Yes || Yes" in {
val leftSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'))
val rightSideYes = Yes(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'))
val fact = leftSideYes || rightSideYes
fact shouldBe a [Yes]
fact.rawFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.rawMidSentenceFailureMessage should be (Resources.rawWasNotGreaterThan)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawWasGreaterThan)
fact.failureMessage should be (Resources.wasNotGreaterThan('e'.pretty, 'b'.pretty))
fact.negatedFailureMessage should be (Resources.wasGreaterThan('e'.pretty, 'b'.pretty))
fact.midSentenceFailureMessage should be (Resources.wasNotGreaterThan('e'.pretty, 'b'.pretty))
fact.midSentenceNegatedFailureMessage should be (Resources.wasGreaterThan('e'.pretty, 'b'.pretty))
fact.failureMessageArgs should be (Vector('e', 'b'))
fact.negatedFailureMessageArgs should be (Vector('e', 'b'))
fact.composite should be (false)
}
}
"should be parenthesize composite facts" - {
"for non-composite || composite" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), false)
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), true)
val fact = leftSideNo || rightSideNo
fact.rawFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.rawNegatedFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawRightParensCommaAnd)
fact.composite should be (true)
}
"for composite || non-composite" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), true)
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), false)
val fact = leftSideNo || rightSideNo
fact.rawFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.rawNegatedFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawLeftParensCommaAnd)
fact.composite should be (true)
}
"for composite || composite" in {
val leftSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'),Vector('e', 'b'), true)
val rightSideNo = No(Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Resources.rawWasNotGreaterThan, Resources.rawWasGreaterThan, Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'),Vector('e', 'd'), true)
val fact = leftSideNo || rightSideNo
fact.rawFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.rawNegatedFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.rawMidSentenceFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.rawMidSentenceNegatedFailureMessage should be (Resources.rawBothParensCommaAnd)
fact.composite should be (true)
}
}
}
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/EitherValues.scala | <filename>scalatest/src/main/scala/org/scalatest/EitherValues.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 org.scalatest.exceptions.StackDepthExceptionHelper.getStackDepthFun
import org.scalatest.exceptions.TestFailedException
/**
* Trait that provides an implicit conversion that adds <code>left.value</code> and <code>right.value</code> methods
* to <code>Either</code>, which will return the selected value of the <code>Either</code> if defined,
* or throw <code>TestFailedException</code> if not.
*
* <p>
* This construct allows you to express in one statement that an <code>Either</code> should be <em>left</em> or <em>right</em>
* and that its value should meet some expectation. Here's are some examples:
* </p>
*
* <pre class="stHighlight">
* either1.right.value should be > 9
* either2.left.value should be ("Muchas problemas")
* </pre>
*
* <p>
* Or, using assertions instead of matcher expressions:
* </p>
*
* <pre class="stHighlight">
* assert(either1.right.value > 9)
* assert(either2.left.value === "Muchas problemas")
* </pre>
*
* <p>
* Were you to simply invoke <code>right.get</code> or <code>left.get</code> on the <code>Either</code>,
* if the <code>Either</code> wasn't defined as expected (<em>e.g.</em>, it was a <code>Left</code> when you expected a <code>Right</code>), it
* would throw a <code>NoSuchElementException</code>:
* </p>
*
* <pre class="stHighlight">
* val either: Either[String, Int] = Left("Muchas problemas")
*
* either.right.get should be > 9 // either.right.get throws NoSuchElementException
* </pre>
*
* <p>
* The <code>NoSuchElementException</code> would cause the test to fail, but without providing a <a href="exceptions/StackDepth.html">stack depth</a> pointing
* to the failing line of test code. This stack depth, provided by <a href="exceptions/TestFailedException.html"><code>TestFailedException</code></a> (and a
* few other ScalaTest exceptions), makes it quicker for
* users to navigate to the cause of the failure. Without <code>EitherValues</code>, to get
* a stack depth exception you would need to make two statements, like this:
* </p>
*
* <pre class="stHighlight">
* val either: Either[String, Int] = Left("Muchas problemas")
*
* either should be ('right) // throws TestFailedException
* either.right.get should be > 9
* </pre>
*
* <p>
* The <code>EitherValues</code> trait allows you to state that more concisely:
* </p>
*
* <pre class="stHighlight">
* val either: Either[String, Int] = Left("Muchas problemas")
*
* either.right.value should be > 9 // either.right.value throws TestFailedException
* </pre>
*/
trait EitherValues {
import scala.language.implicitConversions
/**
* Implicit conversion that adds a <code>value</code> method to <code>LeftProjection</code>.
*
* @param either the <code>LeftProjection</code> on which to add the <code>value</code> method
*/
implicit def convertLeftProjectionToValuable[L, R](leftProj: Either.LeftProjection[L, R]) = new LeftValuable(leftProj)
/**
* Implicit conversion that adds a <code>value</code> method to <code>RightProjection</code>.
*
* @param either the <code>RightProjection</code> on which to add the <code>value</code> method
*/
implicit def convertRightProjectionToValuable[L, R](rightProj: Either.RightProjection[L, R]) = new RightValuable(rightProj)
/**
* Wrapper class that adds a <code>value</code> method to <code>LeftProjection</code>, allowing
* you to make statements like:
*
* <pre class="stHighlight">
* either.left.value should be > 9
* </pre>
*
* @param leftProj A <code>LeftProjection</code> to convert to <code>LeftValuable</code>, which provides the
* <code>value</code> method.
*/
class LeftValuable[L, R](leftProj: Either.LeftProjection[L, R]) {
/**
* Returns the <code>Left</code> value contained in the wrapped <code>LeftProjection</code>, if defined as a <code>Left</code>, else throws <code>TestFailedException</code> with
* a detail message indicating the <code>Either</code> was defined as a <code>Right</code>, not a <code>Left</code>.
*/
def value: L = {
try {
leftProj.get
}
catch {
case cause: NoSuchElementException =>
throw new TestFailedException(sde => Some(Resources.eitherLeftValueNotDefined), Some(cause), getStackDepthFun("EitherValues.scala", "value"))
}
}
}
/**
* Wrapper class that adds a <code>value</code> method to <code>RightProjection</code>, allowing
* you to make statements like:
*
* <pre class="stHighlight">
* either.right.value should be > 9
* </pre>
*
* @param rightProj A <code>RightProjection</code> to convert to <code>RightValuable</code>, which provides the
* <code>value</code> method.
*/
class RightValuable[L, R](rightProj: Either.RightProjection[L, R]) {
/**
* Returns the <code>Right</code> value contained in the wrapped <code>RightProjection</code>, if defined as a <code>Right</code>, else throws <code>TestFailedException</code> with
* a detail message indicating the <code>Either</code> was defined as a <code>Right</code>, not a <code>Left</code>.
*/
def value: R = {
try {
rightProj.get
}
catch {
case cause: NoSuchElementException =>
throw new TestFailedException(sde => Some(Resources.eitherRightValueNotDefined), Some(cause), getStackDepthFun("EitherValues.scala", "value"))
}
}
}
}
/**
* Companion object that facilitates the importing of <code>ValueEither</code> members as
* an alternative to mixing it in. One use case is to import <code>EitherValues</code>'s members so you can use
* <code>left.value</code> and <code>right.value</code> on <code>Either</code> in the Scala interpreter:
*
* <pre class="stREPL">
* $ scala -cp scalatest-1.7.jar
* Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_29).
* Type in expressions to have them evaluated.
* Type :help for more information.
*
* scala> import org.scalatest._
* import org.scalatest._
*
* scala> import matchers.Matchers._
* import matchers.Matchers._
*
* scala> import EitherValues._
* import EitherValues._
*
* scala> val e: Either[String, Int] = Left("Muchas problemas")
* e: Either[String,Int] = Left(Muchas problemas)
*
* scala> e.left.value should be ("Muchas problemas")
*
* scala> e.right.value should be < 9
* org.scalatest.TestFailedException: The Either on which rightValue was invoked was not defined.
* at org.scalatest.EitherValues$RightValuable.value(EitherValues.scala:148)
* at .<init>(<console>:18)
* ...
* </pre>
*/
object EitherValues extends EitherValues
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/ExampleMatcherSpec.scala | package test
import org.scalatest._
import Matchers._
class ExampleMatcherSpec extends FunSpec {
describe("Equal matcher") {
it("should do nothing when LHS is equal to RHS") {
val a = 1
val b = 1
a should equal (b)
}
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/NoElementsOfContainMatcherSpec.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 collection.GenTraversable
import SharedHelpers._
import Matchers._
import org.scalactic.Entry
class NoElementsOfContainMatcherSpec extends Spec {
object `noElementsOf ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
e.message should be (Some(FailureMessages.containedAtLeastOneOf(left, right)))
e.failedCodeFileName should be (Some("NoElementsOfContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeed when left List contains elements available in right List` {
List(1, 2, 3, 4, 5) should contain noElementsOf Seq(6, 7, 8)
Array(1, 2, 3, 4, 5) should contain noElementsOf Seq(6, 7, 8)
javaList(1, 2, 3, 4, 5) should contain noElementsOf Seq(6, 7, 8)
Set(1, 2, 3, 4, 5) should contain noElementsOf Seq(6, 7, 8)
javaSet(1, 2, 3, 4, 5) should contain noElementsOf Seq(6, 7, 8)
Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four", 5 -> "five") should contain noElementsOf Seq(6 -> "six", 7 -> "seven", 8 -> "eight")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"), Entry(4, "four"), Entry(5, "five")) should contain noElementsOf Seq(Entry(6, "six"), Entry(7, "seven"), Entry(8, "eight"))
}
def `should succeed when left list contains none of right list` {
List(1, 2, 3) should contain noElementsOf Seq(7, 8)
Array(1, 2, 3) should contain noElementsOf Seq(7, 8)
javaList(1, 2, 3) should contain noElementsOf Seq(7, 8)
Set(1, 2, 3) should contain noElementsOf Seq(7, 8)
javaSet(1, 2, 3) should contain noElementsOf Seq(7, 8)
Map(1 -> "one", 2 -> "two", 3 -> "three") should contain noElementsOf Seq(7 -> "seven", 8 -> "eight")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain noElementsOf Seq(Entry(7, "seven"), Entry(8, "eight"))
}
def `should throw NotAllowedException when noElementsOf contains duplicate element` {
val e1 = intercept[exceptions.NotAllowedException] {
List(1, 2, 3) should contain noElementsOf Seq(6, 8, 6)
}
e1.getMessage() should be (FailureMessages.noElementsOfDuplicate)
val e2 = intercept[exceptions.NotAllowedException] {
Set(1, 2, 3) should contain noElementsOf Seq(6, 8, 6)
}
e2.getMessage() should be (FailureMessages.noElementsOfDuplicate)
val e3 = intercept[exceptions.NotAllowedException] {
Array(1, 2, 3) should contain noElementsOf Seq(6, 8, 6)
}
e3.getMessage() should be (FailureMessages.noElementsOfDuplicate)
}
def `should throw TestFailedException with correct stack depth and message when left List contains element in right List` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain noElementsOf Seq(0, 3, 8)
}
checkStackDepth(e1, left1, Seq(0, 3, 8), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain noElementsOf Seq(0, 3, 8)
}
checkStackDepth(e2, left2, Seq(0, 3, 8), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain noElementsOf Seq(0 -> "zero", 3 -> "three", 8 -> "eight")
}
checkStackDepth(e3, left3, Seq(0 -> "zero", 3 -> "three", 8 -> "eight"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain noElementsOf Seq(Entry(0, "zero"), Entry(3, "three"), Entry(8, "eight"))
}
checkStackDepth(e4, left4, Seq(Entry(0, "zero"), Entry(3, "three"), Entry(8, "eight")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain noElementsOf Seq(0, 3, 8)
}
checkStackDepth(e5, left5, Seq(0, 3, 8), thisLineNumber - 2)
}
}
object `not noElementsOf ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: GenTraversable[Any], lineNumber: Int) {
val leftText = FailureMessages.decorateToStringValue(left)
e.message should be (Some(FailureMessages.didNotContainAtLeastOneOf(left, right)))
e.failedCodeFileName should be (Some("NoElementsOfContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeed when left List contains element in right List` {
List(1, 2, 3) should not contain noElementsOf (Seq(0, 2, 8))
Array(1, 2, 3) should not contain noElementsOf (Seq(0, 2, 8))
javaList(1, 2, 3) should not contain noElementsOf (Seq(0, 2, 8))
Set(1, 2, 3) should not contain noElementsOf (Seq(0, 2, 8))
javaSet(1, 2, 3) should not contain noElementsOf (Seq(0, 2, 8))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain noElementsOf (Seq(0 -> "zero", 2 -> "two", 8 -> "eight"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain noElementsOf (Seq(Entry(0, "zero"), Entry(2, "two"), Entry(8, "eight")))
}
def `should throw TestFailedException with correct stack depth and message when left List contains only element in right List in same order` {
val left1 = List(1, 2, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should not contain noElementsOf (Seq(7, 8, 9))
}
checkStackDepth(e1, left1, Seq(7, 8, 9), thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should not contain noElementsOf (Seq(7, 8, 9))
}
checkStackDepth(e2, left2, Seq(7, 8, 9), thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should not contain noElementsOf (Seq(7 -> "seven", 8 -> "eight", 9 -> "nine"))
}
checkStackDepth(e3, left3, Seq(7 -> "seven", 8 -> "eight", 9 -> "nine"), thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should not contain noElementsOf (Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")))
}
checkStackDepth(e4, left4, Seq(Entry(7, "seven"), Entry(8, "eight"), Entry(9, "nine")), thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should not contain noElementsOf (Seq(7, 8, 9))
}
checkStackDepth(e5, left5, Seq(7, 8, 9), thisLineNumber - 2)
}
}
}
|
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/BeforeAndAfterAllProp.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.junit.JUnit3Suite
import org.scalatest.junit.JUnitSuite
import org.junit.Test
import org.testng.annotations.{Test => TestNG }
import org.scalatest.testng.TestNGSuite
import SharedHelpers._
class BeforeAndAfterAllProp extends AllSuiteProp {
type FixtureServices = BeforeAndAfterAllPropFixtureServices
def spec = new ExampleBeforeAndAfterAllPropSpec
def fixtureSpec = new ExampleBeforeAndAfterAllPropFixtureSpec
def junit3Suite = new ExampleBeforeAndAfterAllPropJUnit3Suite
def junitSuite = new ExampleBeforeAndAfterAllPropJUnitSuite
def testngSuite = new ExampleBeforeAndAfterAllPropTestNGSuite
def funSuite = new ExampleBeforeAndAfterAllPropFunSuite
def fixtureFunSuite = new ExampleBeforeAndAfterAllPropFixtureFunSuite
def funSpec = new ExampleBeforeAndAfterAllPropFunSpec
def fixtureFunSpec = new ExampleBeforeAndAfterAllPropFixtureFunSpec
def featureSpec = new ExampleBeforeAndAfterAllPropFeatureSpec
def fixtureFeatureSpec = new ExampleBeforeAndAfterAllPropFixtureFeatureSpec
def flatSpec = new ExampleBeforeAndAfterAllPropFlatSpec
def fixtureFlatSpec = new ExampleBeforeAndAfterAllPropFixtureFlatSpec
def freeSpec = new ExampleBeforeAndAfterAllPropFreeSpec
def fixtureFreeSpec = new ExampleBeforeAndAfterAllPropFixtureFreeSpec
def propSpec = new ExampleBeforeAndAfterAllPropPropSpec
def fixturePropSpec = new ExampleBeforeAndAfterAllPropFixturePropSpec
def wordSpec = new ExampleBeforeAndAfterAllPropWordSpec
def fixtureWordSpec = new ExampleBeforeAndAfterAllPropFixtureWordSpec
def pathFreeSpec = new ExampleBeforeAndAfterAllPropPathFreeSpec
def pathFunSpec = new ExampleBeforeAndAfterAllPropPathFunSpec
test("BeforeAndAfterAll should call beforeAll before any test starts, and call afterAll after all tests completed") {
forAll(examples.filter(_.included)) { suite =>
if (suite.included) {
val rep = new EventRecordingReporter()
val dist = new TestConcurrentDistributor(2)
suite.run(None, Args(reporter = rep, distributor = Some(dist)))
dist.waitUntilDone()
// should call beforeAll before any test starts
val beforeAllTime = suite.beforeAllTime
val testStartingEvents = rep.testStartingEventsReceived
testStartingEvents should have size 3
testStartingEvents.foreach { testStarting =>
beforeAllTime should be <= testStarting.timeStamp
}
// should call afterAll after all tests completed
val afterAllTime = suite.afterAllTime
val testSucceededEvents = rep.testSucceededEventsReceived
testSucceededEvents should have size 3
testSucceededEvents.foreach { testSucceeded =>
afterAllTime should be >= testSucceeded.timeStamp
}
}
}
}
}
trait BeforeAndAfterAllPropFixtureServices {
def included = this match {
case _: JUnit3Suite => false
case _: JUnitSuite => false
case _: TestNGSuite => false
case _: path.FreeSpec => false
case _: path.FunSpec => false
case _ => true
}
@volatile var beforeAllTime: Long = 0
@volatile var afterAllTime: Long = 0
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropSpec extends Spec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
object `Scope 1` {
def `Test 1` { Thread.sleep(10) }
def `Test 2` { Thread.sleep(10) }
def `Test 3` { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureSpec extends fixture.Spec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
object `Scope 1` {
def `Test 1`(fixture: String) { Thread.sleep(10) }
def `Test 2`(fixture: String) { Thread.sleep(10) }
def `Test 3`(fixture: String) { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
// Not supported as JUnit3Suite cannot use ParallelTestExecution
@DoNotDiscover
class ExampleBeforeAndAfterAllPropJUnit3Suite extends JUnit3Suite with BeforeAndAfterAllPropFixtureServices { }
// Not supported as JUnitSuite cannot use ParallelTestExecution
@DoNotDiscover
class ExampleBeforeAndAfterAllPropJUnitSuite extends JUnitSuite with BeforeAndAfterAllPropFixtureServices { }
// Not supported as JUnitSuite cannot use ParallelTestExecution
@DoNotDiscover
class ExampleBeforeAndAfterAllPropTestNGSuite extends TestNGSuite with BeforeAndAfterAllPropFixtureServices { }
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFunSuite extends FunSuite with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
test("Test 1") { Thread.sleep(10) }
test("Test 2") { Thread.sleep(10) }
test("Test 3") { Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureFunSuite extends fixture.FunSuite with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
test("Test 1") { s => Thread.sleep(10) }
test("Test 2") { s => Thread.sleep(10) }
test("Test 3") { s => Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFunSpec extends FunSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
describe("Scope 1") {
it("Test 1") { Thread.sleep(10) }
it("Test 2") { Thread.sleep(10) }
it("Test 3") { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureFunSpec extends fixture.FunSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
describe("Scope 1") {
it("Test 1") { s => Thread.sleep(10) }
it("Test 2") { s => Thread.sleep(10) }
it("Test 3") { s => Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFeatureSpec extends FeatureSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
feature("Feature 1") {
scenario("Scenario 1") { Thread.sleep(10) }
scenario("Scenario 2") { Thread.sleep(10) }
scenario("Scenario 3") { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureFeatureSpec extends fixture.FeatureSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
feature("Feature 1") {
scenario("Scenario 1") { s => Thread.sleep(10) }
scenario("Scenario 2") { s => Thread.sleep(10) }
scenario("Scenario 3") { s => Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFlatSpec extends FlatSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
"Scope 1" should "do thing 1" in { Thread.sleep(10) }
it should "do thing 2" in { Thread.sleep(10) }
it should "do thing 3" in { Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureFlatSpec extends fixture.FlatSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
"Scope 1" should "do thing 1" in { s => Thread.sleep(10) }
it should "do thing 2" in { s => Thread.sleep(10) }
it should "do thing 3" in { s => Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFreeSpec extends FreeSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
"Scope 1" - {
"Test 1" in { Thread.sleep(10) }
"Test 2" in { Thread.sleep(10) }
"Test 3" in { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureFreeSpec extends fixture.FreeSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
"Scope 1" - {
"Test 1" in { s => Thread.sleep(10) }
"Test 2" in { s => Thread.sleep(10) }
"Test 3" in { s => Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropPropSpec extends PropSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
property("Test 1") { Thread.sleep(10) }
property("Test 2") { Thread.sleep(10) }
property("Test 3") { Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixturePropSpec extends fixture.PropSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
property("Test 1") { s => Thread.sleep(10) }
property("Test 2") { s => Thread.sleep(10) }
property("Test 3") { s => Thread.sleep(10) }
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropWordSpec extends WordSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with ParallelTestExecution {
"Scope 1" should {
"Test 1" in { Thread.sleep(10) }
"Test 2" in { Thread.sleep(10) }
"Test 3" in { Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
@DoNotDiscover
class ExampleBeforeAndAfterAllPropFixtureWordSpec extends fixture.WordSpec with BeforeAndAfterAll with BeforeAndAfterAllPropFixtureServices with StringFixture with ParallelTestExecution {
"Scope 1" should {
"Test 1" in { s => Thread.sleep(10) }
"Test 2" in { s => Thread.sleep(10) }
"Test 3" in { s => Thread.sleep(10) }
}
override protected def beforeAll() {
beforeAllTime = System.currentTimeMillis
}
override protected def afterAll() {
afterAllTime = System.currentTimeMillis
}
}
// Not supported as path.FreeSpec cannot use ParallelTestExecution
@DoNotDiscover
class ExampleBeforeAndAfterAllPropPathFreeSpec extends path.FreeSpec with BeforeAndAfterAllPropFixtureServices { }
// Not supported as path.FunSpec cannot use ParallelTestExecution
@DoNotDiscover
class ExampleBeforeAndAfterAllPropPathFunSpec extends path.FunSpec with BeforeAndAfterAllPropFixtureServices { }
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/concurrent/AbstractPatienceConfiguration.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.concurrent
import org.scalatest.time.{Span, Millis}
/**
* Trait that defines an abstract <code>patienceConfig</code> method that is implemented in <a href="PatienceConfiguration.html"><code>PatienceConfiguration</code></a> and can
* be overriden in stackable modification traits such as <a href="IntegrationPatience.html"><code>IntegrationPatience</code></a>.
*
* <p>
* The main purpose of <code>AbstractPatienceConfiguration</code> is to differentiate core <code>PatienceConfiguration</code>
* traits, such as <a href="Eventually.html"><code>Eventually</code></a> and <a href="AsyncAssertions.html"><code>AsyncAssertions</code></a>, from stackable
* modification traits for <code>PatienceConfiguration</code>s such as <code>IntegrationPatience</code>.
* Because these stackable traits extend <code>AbstractPatienceConfiguration</code>
* instead of <a href="../Suite.html"><code>Suite</code></a>, you can't simply mix in a stackable trait:
* </p>
*
* <pre class="stHighlight">
* class ExampleSpec extends FunSpec with IntegrationPatience // Won't compile
* </pre>
*
* <p>
* The previous code is undesirable because <code>IntegrationPatience</code> would have no affect on the class. Instead, you need to mix
* in a core <code>PatienceConfiguration</code> trait and mix the stackable <code>IntegrationPatience</code> trait
* into that, like this:
* </p>
*
* <pre class="stHighlight">
* class ExampleSpec extends FunSpec with Eventually with IntegrationPatience // Compiles fine
* </pre>
*
* <p>
* The previous code is better because <code>IntegrationPatience</code> does have an effect: it modifies the behavior
* of <code>Eventually</code>.
* </p>
*
* @author <NAME>
*/
trait AbstractPatienceConfiguration extends ScaledTimeSpans {
/**
* Configuration object for asynchronous constructs, such as those provided by traits <a href="Eventually.html"><code>Eventually</code></a> and
* <a href="AsyncAssertions.html"><code>AsyncAssertions</code></a>.
*
* <p>
* The default values for the parameters are:
* </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"><strong>Configuration Parameter</strong></th><th style="background-color: #CCCCCC; border-width: 1px; padding: 3px; text-align: center; border: 1px solid black"><strong>Default Value</strong></th></tr>
* <tr>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
* <code>timeout</code>
* </td>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
* <code>scaled(150 milliseconds)</code>
* </td>
* </tr>
* <tr>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
* <code>interval</code>
* </td>
* <td style="border-width: 1px; padding: 3px; border: 1px solid black; text-align: center">
* <code>scaled(15 milliseconds)</code>
* </td>
* </tr>
* </table>
*
* @param timeout the maximum amount of time to wait for an asynchronous operation to complete before giving up and throwing
* <code>TestFailedException</code>.
* @param interval the amount of time to sleep between each check of the status of an asynchronous operation when polling
*
* @author <NAME>
* @author <NAME>
*/
final case class PatienceConfig(timeout: Span = scaled(Span(150, Millis)), interval: Span = scaled(Span(15, Millis)))
/**
* Returns a <code>PatienceConfig</code> value providing default configuration values if implemented and made implicit in subtraits.
*/
def patienceConfig: PatienceConfig
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/fixture/ExampleFlatSpec.scala | package test.fixture
import org.scalatest._
class ExampleFlatSpec extends fixture.FlatSpec {
type FixtureParam = String
def withFixture(test: OneArgTest): Outcome = {
test("hi")
}
"An empty Set" should "have size 0" in { f =>
assert(Set.empty.size == 0)
}
it should "produce NoSuchElementException when head is invoked" in { f =>
intercept[NoSuchElementException] {
Set.empty.head
}
}
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/SharedHelpers.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.events._
import java.util.concurrent.Executors
import java.io.File
import scala.annotation.tailrec
import scala.collection.GenTraversable
import scala.collection.GenMap
import scala.collection.SortedSet
import scala.collection.SortedMap
import FailureMessages.decorateToStringValue
import org.scalactic.Entry
import org.scalatest.exceptions.StackDepthException
object SharedHelpers extends Assertions {
object SilentReporter extends Reporter {
def apply(event: Event) = ()
}
object NoisyReporter extends Reporter {
def apply(event: Event): Unit = { println(event) }
}
class TestDurationReporter extends Reporter {
var testSucceededWasFiredAndHadADuration = false
var testFailedWasFiredAndHadADuration = false
override def apply(event: Event) {
event match {
case event: TestSucceeded => testSucceededWasFiredAndHadADuration = event.duration.isDefined
case event: TestFailed => testFailedWasFiredAndHadADuration = event.duration.isDefined
case _ =>
}
}
}
class SuiteDurationReporter extends Reporter {
var suiteCompletedWasFiredAndHadADuration = false
var suiteAbortedWasFiredAndHadADuration = false
override def apply(event: Event) {
event match {
case event: SuiteCompleted => suiteCompletedWasFiredAndHadADuration = event.duration.isDefined
case event: SuiteAborted => suiteAbortedWasFiredAndHadADuration = event.duration.isDefined
case _ =>
}
}
}
class PendingReporter extends Reporter {
var testPendingWasFired = false
override def apply(event: Event) {
event match {
case _: TestPending => testPendingWasFired = true
case _ =>
}
}
}
class EventRecordingReporter extends Reporter {
private var eventList: List[Event] = List()
def eventsReceived = eventList.reverse
def testSucceededEventsReceived: List[TestSucceeded] = {
eventsReceived filter {
case event: TestSucceeded => true
case _ => false
} map {
case event: TestSucceeded => event
case _ => throw new RuntimeException("should never happen")
}
}
def testStartingEventsReceived: List[TestStarting] = {
eventsReceived filter {
case event: TestStarting => true
case _ => false
} map {
case event: TestStarting => event
case _ => throw new RuntimeException("should never happen")
}
}
// Why doesn't this work:
// for (event: TestSucceeded <- eventsReceived) yield event
def infoProvidedEventsReceived: List[InfoProvided] = {
eventsReceived filter {
case event: InfoProvided => true
case _ => false
} map {
case event: InfoProvided => event
case _ => throw new RuntimeException("should never happen")
}
}
def noteProvidedEventsReceived: List[NoteProvided] = {
eventsReceived filter {
case event: NoteProvided => true
case _ => false
} map {
case event: NoteProvided => event
case _ => throw new RuntimeException("should never happen")
}
}
def alertProvidedEventsReceived: List[AlertProvided] = {
eventsReceived filter {
case event: AlertProvided => true
case _ => false
} map {
case event: AlertProvided => event
case _ => throw new RuntimeException("should never happen")
}
}
def markupProvidedEventsReceived: List[MarkupProvided] = {
eventsReceived filter {
case event: MarkupProvided => true
case _ => false
} map {
case event: MarkupProvided => event
case _ => throw new RuntimeException("should never happen")
}
}
def scopeOpenedEventsReceived: List[ScopeOpened] = {
eventsReceived filter {
case event: ScopeOpened => true
case _ => false
} map {
case event: ScopeOpened => event
case _ => throw new RuntimeException("should never happen")
}
}
def scopeClosedEventsReceived: List[ScopeClosed] = {
eventsReceived filter {
case event: ScopeClosed => true
case _ => false
} map {
case event: ScopeClosed => event
case _ => throw new RuntimeException("should never happen")
}
}
def scopePendingEventsReceived: List[ScopePending] = {
eventsReceived filter {
case event: ScopePending => true
case _ => false
} map {
case event: ScopePending => event
case _ => throw new RuntimeException("should never happen")
}
}
def testPendingEventsReceived: List[TestPending] = {
eventsReceived filter {
case event: TestPending => true
case _ => false
} map {
case event: TestPending => event
case _ => throw new RuntimeException("should never happen")
}
}
def testCanceledEventsReceived: List[TestCanceled] = {
eventsReceived filter {
case event: TestCanceled => true
case _ => false
} map {
case event: TestCanceled => event
case _ => throw new RuntimeException("should never happen")
}
}
def testFailedEventsReceived: List[TestFailed] = {
eventsReceived filter {
case event: TestFailed => true
case _ => false
} map {
case event: TestFailed => event
case _ => throw new RuntimeException("should never happen")
}
}
def testIgnoredEventsReceived: List[TestIgnored] = {
eventsReceived filter {
case event: TestIgnored => true
case _ => false
} map {
case event: TestIgnored => event
case _ => throw new RuntimeException("should never happen")
}
}
def suiteStartingEventsReceived: List[SuiteStarting] = {
eventsReceived filter {
case event: SuiteStarting => true
case _ => false
} map {
case event: SuiteStarting => event
case _ => throw new RuntimeException("should never happen")
}
}
def suiteCompletedEventsReceived: List[SuiteCompleted] = {
eventsReceived filter {
case event: SuiteCompleted => true
case _ => false
} map {
case event: SuiteCompleted => event
case _ => throw new RuntimeException("should never happen")
}
}
def suiteAbortedEventsReceived: List[SuiteAborted] = {
eventsReceived filter {
case event: SuiteAborted => true
case _ => false
} map {
case event: SuiteAborted => event
case _ => throw new RuntimeException("should never happen")
}
}
def apply(event: Event) {
eventList ::= event
}
}
def getIndexesForTestInformerEventOrderTests(suite: Suite, testName: String, infoMsg: String): (Int, Int) = {
val myRep = new EventRecordingReporter
suite.run(None, Args(myRep))
val indexedList = myRep.eventsReceived.zipWithIndex
val testStartingOption = indexedList.find(_._1.isInstanceOf[TestStarting])
val testSucceededOption = indexedList.find(_._1.isInstanceOf[TestSucceeded])
assert(testStartingOption.isDefined, "TestStarting for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
assert(testSucceededOption.isDefined, "TestSucceeded for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
val testStartingIndex = testStartingOption.get._2
val testSucceededIndex = testSucceededOption.get._2
val testStarting = testStartingOption.get._1.asInstanceOf[TestStarting]
val testSucceeded = testSucceededOption.get._1.asInstanceOf[TestSucceeded]
val recordedEvents = testSucceeded.recordedEvents
val infoProvidedOption = recordedEvents.find {
case event: InfoProvided => event.message == infoMsg
case _ => false
}
assert(infoProvidedOption.isDefined, "InfoProvided for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
(testStartingIndex, testSucceededIndex)
}
def getIndexesForInformerEventOrderTests(suite: Suite, testName: String, infoMsg: String): (Int, Int, Int) = {
val myRep = new EventRecordingReporter
suite.run(None, Args(myRep))
val indexedList = myRep.eventsReceived.zipWithIndex
val testStartingOption = indexedList.find(_._1.isInstanceOf[TestStarting])
val infoProvidedOption = indexedList.find {
case (event: InfoProvided, index) => event.message == infoMsg
case _ => false
}
val testSucceededOption = indexedList.find(_._1.isInstanceOf[TestSucceeded])
assert(testStartingOption.isDefined, "TestStarting for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
assert(infoProvidedOption.isDefined, "InfoProvided for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
assert(testSucceededOption.isDefined, "TestSucceeded for Suite='" + suite.suiteId + "', testName='" + testName + "' not defined.")
val testStartingIndex = testStartingOption.get._2
val infoProvidedIndex = infoProvidedOption.get._2
val testSucceededIndex = testSucceededOption.get._2
val testStarting = testStartingOption.get._1.asInstanceOf[TestStarting]
val infoProvided = infoProvidedOption.get._1.asInstanceOf[InfoProvided]
val testSucceeded = testSucceededOption.get._1.asInstanceOf[TestSucceeded]
assert(testStarting.testName === testName, "TestStarting.testName expected to be '" + testName + "', but got '" + testStarting.testName + "'.")
assert(infoProvided.message === infoMsg, "InfoProvide.message expected to be '" + infoMsg + "', but got '" + infoProvided.message + "'.")
assert(testSucceeded.testName === testName, "TestSucceeded.testName expected to be '" + testName + "', but got '" + testSucceeded.testName + "'.")
(infoProvidedIndex, testStartingIndex, testSucceededIndex)
}
def getIndentedTextFromInfoProvided(suite: Suite): IndentedText = {
val myRep = new EventRecordingReporter
suite.run(None, Args(myRep))
val infoProvidedOption = myRep.eventsReceived.find(_.isInstanceOf[InfoProvided])
infoProvidedOption match {
case Some(infoProvided: InfoProvided) =>
infoProvided.formatter match {
case Some(indentedText: IndentedText) => indentedText
case _ => fail("An InfoProvided was received that didn't include an IndentedText formatter: " + infoProvided.formatter)
}
case _ => fail("No InfoProvided was received by the Reporter during the run.")
}
}
def getIndentedTextFromTestInfoProvided(suite: Suite): IndentedText = {
val myRep = new EventRecordingReporter
suite.run(None, Args(myRep))
val recordedEvents: Seq[Event] = myRep.eventsReceived.find { e =>
e match {
case testSucceeded: TestSucceeded =>
true
case testFailed: TestFailed =>
true
case testPending: TestPending =>
true
case testCanceled: TestCanceled =>
true
case _ =>
false
}
} match {
case Some(testCompleted) =>
testCompleted match {
case testSucceeded: TestSucceeded =>
testSucceeded.recordedEvents
case testFailed: TestFailed =>
testFailed.recordedEvents
case testPending: TestPending =>
testPending.recordedEvents
case testCanceled: TestCanceled =>
testCanceled.recordedEvents
case _ => throw new RuntimeException("should never get here")
}
case None =>
fail("Test completed event is expected but not found.")
}
assert(recordedEvents.size === 1)
recordedEvents(0) match {
case ip: InfoProvided =>
ip.formatter match {
case Some(indentedText: IndentedText) => indentedText
case _ => fail("An InfoProvided was received that didn't include an IndentedText formatter: " + ip.formatter)
}
case _ => fail("No InfoProvided was received by the Reporter during the run.")
}
}
def ensureTestFailedEventReceived(suite: Suite, testName: String) {
val reporter = new EventRecordingReporter
suite.run(None, Args(reporter))
val testFailedEvent = reporter.eventsReceived.find(_.isInstanceOf[TestFailed])
assert(testFailedEvent.isDefined)
assert(testFailedEvent.get.asInstanceOf[TestFailed].testName === testName)
}
def ensureTestFailedEventReceivedWithCorrectMessage(suite: Suite, testName: String, expectedMessage: String) {
val reporter = new EventRecordingReporter
suite.run(None, Args(reporter))
val testFailedEvent = reporter.eventsReceived.find(_.isInstanceOf[TestFailed])
assert(testFailedEvent.isDefined)
assert(testFailedEvent.get.asInstanceOf[TestFailed].testName == testName)
assert(testFailedEvent.get.asInstanceOf[TestFailed].message == expectedMessage)
}
def thisLineNumber = {
val st = Thread.currentThread.getStackTrace
if (!st(2).getMethodName.contains("thisLineNumber"))
st(2).getLineNumber
else
st(3).getLineNumber
}
class TestIgnoredTrackingReporter extends Reporter {
var testIgnoredReceived = false
var lastEvent: Option[TestIgnored] = None
def apply(event: Event) {
event match {
case event: TestIgnored =>
testIgnoredReceived = true
lastEvent = Some(event)
case _ =>
}
}
}
class TestConcurrentDistributor(poolSize: Int) extends tools.ConcurrentDistributor(Args(reporter = SilentReporter), Executors.newFixedThreadPool(poolSize)) {
override def apply(suite: Suite, tracker: Tracker) {
throw new UnsupportedOperationException("Please use apply with args.")
}
}
def getIndex[T](xs: GenTraversable[T], value: T): Int = {
@tailrec
def getIndexAcc[T](itr: Iterator[T], count: Int): Int = {
if (itr.hasNext) {
val next = itr.next
if (next == value)
count
else
getIndexAcc(itr, count + 1)
}
else
-1
}
getIndexAcc(xs.toIterator, 0)
}
def getKeyIndex[K, V](xs: GenMap[K, V], value: K): Int = {
@tailrec
def getIndexAcc[K, V](itr: Iterator[(K, V)], count: Int): Int = {
if (itr.hasNext) {
val next = itr.next
if (next._1 == value)
count
else
getIndexAcc(itr, count + 1)
}
else
-1
}
getIndexAcc(xs.toIterator, 0)
}
def getIndex(xs: java.util.Collection[_], value: Any): Int = {
@tailrec
def getIndexAcc(itr: java.util.Iterator[_], count: Int): Int = {
if (itr.hasNext) {
val next = itr.next
if (next == value)
count
else
getIndexAcc(itr, count + 1)
}
else
-1
}
getIndexAcc(xs.iterator, 0)
}
def getIndex[K, V](xs: java.util.Map[K, V], value: java.util.Map.Entry[K, V]): Int = {
@tailrec
def getIndexAcc(itr: java.util.Iterator[java.util.Map.Entry[K, V]], count: Int): Int = {
if (itr.hasNext) {
val next = itr.next
if (next == value)
count
else
getIndexAcc(itr, count + 1)
}
else
-1
}
getIndexAcc(xs.entrySet.iterator, 0)
}
def getKeyIndex[K, V](xs: java.util.Map[K, V], value: K): Int = {
@tailrec
def getIndexAcc[K, V](itr: java.util.Iterator[java.util.Map.Entry[K, V]], count: Int): Int = {
if (itr.hasNext) {
val next = itr.next
if (next.getKey == value)
count
else
getIndexAcc(itr, count + 1)
}
else
-1
}
getIndexAcc(xs.entrySet.iterator, 0)
}
def getIndexes[T](xs: GenTraversable[T], values: GenTraversable[T]): GenTraversable[Int] = {
@tailrec
def getIndexesAcc[T](itr: Iterator[T], indexes: IndexedSeq[Int], count: Int): IndexedSeq[Int] = {
if (itr.hasNext) {
val next = itr.next
if (values.exists(_ == next))
getIndexesAcc(itr, indexes :+ count, count + 1)
else
getIndexesAcc(itr, indexes, count + 1)
}
else
indexes
}
val itr = xs.toIterator
getIndexesAcc(itr, IndexedSeq.empty, 0)
}
def getIndexesInJavaCol[T](xs: java.util.Collection[T], values: java.util.Collection[T]): GenTraversable[Int] = {
import collection.JavaConverters._
val javaValues = values.asScala
@tailrec
def getIndexesAcc[T](itr: java.util.Iterator[T], indexes: IndexedSeq[Int], count: Int): IndexedSeq[Int] = {
if (itr.hasNext) {
val next = itr.next
if (javaValues.exists(_ == next))
getIndexesAcc(itr, indexes :+ count, count + 1)
else
getIndexesAcc(itr, indexes, count + 1)
}
else
indexes
}
val itr = xs.iterator
getIndexesAcc(itr, IndexedSeq.empty, 0)
}
@tailrec
final def getNext[T](itr: Iterator[T], predicate: T => Boolean): T = {
val next = itr.next
if (predicate(next))
next
else
getNext(itr, predicate)
}
final def getNextInString(itr: Iterator[Char], predicate: Char => Boolean) =
getNext[Char](itr, predicate)
@tailrec
final def getNextInJavaIterator[T](itr: java.util.Iterator[T], predicate: T => Boolean): T = {
val next = itr.next
if (predicate(next))
next
else
getNextInJavaIterator(itr, predicate)
}
//final def getNextInJavaMap[K, V](map: java.util.Map[K, V], predicate: java.util.Map.Entry[K, V] => Boolean): java.util.Map.Entry[K, V] =
//getNextInJavaIterator(map.entrySet.iterator, predicate)
final def getNextInJavaMap[K, V](itr: java.util.Iterator[java.util.Map.Entry[K, V]], predicate: java.util.Map.Entry[K, V] => Boolean): java.util.Map.Entry[K, V] =
getNextInJavaIterator(itr, predicate)
def getFirst[T](col: GenTraversable[T], predicate: T => Boolean): T =
getNext(col.toIterator, predicate)
def getFirstInJavaCol[T](col: java.util.Collection[T], predicate: T => Boolean): T =
getNextInJavaIterator(col.iterator, predicate)
def getFirstInJavaMap[K, V](map: java.util.Map[K, V], predicate: java.util.Map.Entry[K, V] => Boolean): java.util.Map.Entry[K, V] =
getNextInJavaIterator(map.entrySet.iterator, predicate)
def getFirstInString(str: String, predicate: Char => Boolean): Char =
getNext(str.toCharArray.iterator, predicate)
@tailrec
final def getNextNot[T](itr: Iterator[T], predicate: T => Boolean): T = {
val next = itr.next
if (!predicate(next))
next
else
getNextNot(itr, predicate)
}
@tailrec
final def getNextNotInJavaCol[T](itr: java.util.Iterator[T], predicate: T => Boolean): T = {
val next = itr.next
if (!predicate(next))
next
else
getNextNotInJavaCol(itr, predicate)
}
def getFirstNot[T](col: GenTraversable[T], predicate: T => Boolean): T =
getNextNot(col.toIterator, predicate)
def getFirstEqual[T](col: GenTraversable[T], right: T): T =
getFirst[T](col, _ == right)
def getFirstNotEqual[T](col: GenTraversable[T], right: T): T =
getFirst[T](col, _ != right)
def getFirstEqual[K, V](col: java.util.Map[K, V], right: java.util.Map.Entry[K, V]): java.util.Map.Entry[K, V] =
getFirstInJavaMap[K, V](col, (e: java.util.Map.Entry[K, V]) => e.getKey == right.getKey && e.getValue == right.getValue)
def getFirstNotEqual[K, V](col: java.util.Map[K, V], right: java.util.Map.Entry[K, V]): java.util.Map.Entry[K, V] =
getFirstInJavaMap[K, V](col, (e: java.util.Map.Entry[K, V]) => e.getKey != right.getKey || e.getValue != right.getValue)
def getFirstMoreThanEqual(col: GenTraversable[Int], right: Int): Int =
getFirst[Int](col, _ >= right)
def getFirstLessThanEqual(col: GenTraversable[Int], right: Int): Int =
getFirst[Int](col, _ <= right)
def getFirstMoreThan(col: GenTraversable[Int], right: Int): Int =
getFirst[Int](col, _ > right)
def getFirstLessThan(col: GenTraversable[Int], right: Int): Int =
getFirst[Int](col, _ < right)
def getFirstIsEmpty(col: GenTraversable[String], right: String): String = // right is not used, but to be consistent to other so that easier for code generation
getFirst[String](col, _.isEmpty)
def getFirstIsNotEmpty(col: GenTraversable[String], right: String): String = // right is not used, but to be consistent to other so that easier for code generation
getFirst[String](col, !_.isEmpty)
def getFirstLengthEqual(col: GenTraversable[String], right: Int): String =
getFirst[String](col, _.length == right)
def getFirstLengthNotEqual(col: GenTraversable[String], right: Int): String =
getFirst[String](col, _.length != right)
def getFirstLengthNotEqualLength(col: GenTraversable[String], right: Int): String =
getFirst[String](col, _.length != right)
def getFirstSizeEqual(col: GenTraversable[String], right: Int): String =
getFirst[String](col, _.size == right)
def getFirstSizeNotEqual(col: GenTraversable[String], right: Int): String =
getFirst[String](col, _.size != right)
def getFirstRefEqual[T <: AnyRef](col: GenTraversable[T], right: T): T =
getFirst[T](col, _ eq right)
def getFirstNotRefEqual[T <: AnyRef](col: GenTraversable[T], right: T): T =
getFirst[T](col, _ ne right)
def getFirstStartsWith(col: GenTraversable[String], right: String): String =
getFirst[String](col, _.startsWith(right))
def getFirstNotStartsWith(col: GenTraversable[String], right: String): String =
getFirst[String](col, !_.startsWith(right))
def getFirstEndsWith(col: GenTraversable[String], right: String): String =
getFirst[String](col, _.endsWith(right))
def getFirstNotEndsWith(col: GenTraversable[String], right: String): String =
getFirst[String](col, !_.endsWith(right))
def getFirstInclude(col: GenTraversable[String], right: String): String =
getFirst[String](col, _.indexOf(right) >= 0)
def getFirstNotInclude(col: GenTraversable[String], right: String): String =
getFirst[String](col, _.indexOf(right) < 0)
def getFirstMatches(col: GenTraversable[String], right: String): String =
getFirst[String](col, _.matches(right))
def getFirstNotMatches(col: GenTraversable[String], right: String): String =
getFirst[String](col, !_.matches(right))
def getFirstNot[T](col: java.util.Collection[T], predicate: T => Boolean): T =
getNextNotInJavaCol(col.iterator, predicate)
def getFirstEqual[T](col: java.util.Collection[T], right: T): T =
getFirstInJavaCol[T](col, _ == right)
def getFirstNotEqual[T](col: java.util.Collection[T], right: T): T =
getFirstInJavaCol[T](col, _ != right)
def getFirstMoreThanEqual(col: java.util.Collection[Int], right: Int): Int =
getFirstInJavaCol[Int](col, _ >= right)
def getFirstLessThanEqual(col: java.util.Collection[Int], right: Int): Int =
getFirstInJavaCol[Int](col, _ <= right)
def getFirstMoreThan(col: java.util.Collection[Int], right: Int): Int =
getFirstInJavaCol[Int](col, _ > right)
def getFirstLessThan(col: java.util.Collection[Int], right: Int): Int =
getFirstInJavaCol[Int](col, _ < right)
def getFirstIsEmpty(col: java.util.Collection[String], right: String): String = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[String](col, _.isEmpty)
def getFirstIsNotEmpty(col: java.util.Collection[String], right: String): String = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[String](col, !_.isEmpty)
def getFirstLengthEqual(col: java.util.Collection[String], right: Int): String =
getFirstInJavaCol[String](col, _.length == right)
def getFirstLengthNotEqual(col: java.util.Collection[String], right: Int): String =
getFirstInJavaCol[String](col, _.length != right)
def getFirstLengthNotEqualLength(col: java.util.Collection[String], right: Int): String =
getFirstInJavaCol[String](col, _.length != right)
def getFirstSizeEqual(col: java.util.Collection[String], right: Int): String =
getFirstInJavaCol[String](col, _.size == right)
def getFirstSizeNotEqual(col: java.util.Collection[String], right: Int): String =
getFirstInJavaCol[String](col, _.size != right)
def getFirstRefEqual[T <: AnyRef](col: java.util.Collection[T], right: T): T =
getFirstInJavaCol[T](col, _ eq right)
def getFirstNotRefEqual[T <: AnyRef](col: java.util.Collection[T], right: T): T =
getFirstInJavaCol[T](col, _ ne right)
def getFirstStartsWith(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, _.startsWith(right))
def getFirstNotStartsWith(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, !_.startsWith(right))
def getFirstEndsWith(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, _.endsWith(right))
def getFirstNotEndsWith(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, !_.endsWith(right))
def getFirstInclude(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, _.indexOf(right) >= 0)
def getFirstNotInclude(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, _.indexOf(right) < 0)
def getFirstMatches(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, _.matches(right))
def getFirstNotMatches(col: java.util.Collection[String], right: String): String =
getFirstInJavaCol[String](col, !_.matches(right))
def getFirstSizeEqualGenTraversable[T](col: GenTraversable[GenTraversable[T]], right: Int): GenTraversable[T] =
getFirst[GenTraversable[T]](col, _.size == right)
def getFirstSizeNotEqualGenTraversable[T](col: GenTraversable[GenTraversable[T]], right: Int): GenTraversable[T] =
getFirst[GenTraversable[T]](col, _.size != right)
def getFirstSizeEqualGenTraversableArray[T](col: GenTraversable[Array[T]], right: Int): Array[T] =
getFirst[Array[T]](col, _.size == right)
def getFirstSizeNotEqualGenTraversableArray[T](col: GenTraversable[Array[T]], right: Int): Array[T] =
getFirst[Array[T]](col, _.size != right)
def getFirstIsEmpty[T](col: GenTraversable[GenTraversable[T]], right: T): GenTraversable[T] =
getFirst[GenTraversable[T]](col, _.isEmpty)
def getFirstNotIsEmpty[T](col: GenTraversable[GenTraversable[T]], right: T): GenTraversable[T] =
getFirst[GenTraversable[T]](col, !_.isEmpty)
def getFirstContainGenTraversable[T](col: GenTraversable[GenTraversable[T]], right: T): GenTraversable[T] =
getFirst[GenTraversable[T]](col, _.exists(_ == right))
def getFirstNotContainGenTraversable[T](col: GenTraversable[GenTraversable[T]], right: T): GenTraversable[T] =
getFirst[GenTraversable[T]](col, !_.exists(_ == right))
def getFirstContainGenTraversableArray[T](col: GenTraversable[Array[T]], right: T): Array[T] =
getFirst[Array[T]](col, _.exists(_ == right))
def getFirstNotContainGenTraversableArray[T](col: GenTraversable[Array[T]], right: T): Array[T] =
getFirst[Array[T]](col, !_.exists(_ == right))
def getFirstContainKey[K, V](col: GenTraversable[GenMap[K, V]], right: K): GenMap[K, V] =
getFirst[GenMap[K, V]](col, _.exists(_._1 == right))
def getFirstNotContainKey[K, V](col: GenTraversable[GenMap[K, V]], right: K): GenMap[K, V] =
getFirst[GenMap[K, V]](col, !_.exists(_._1 == right))
def getFirstContainValue[K, V](col: GenTraversable[GenMap[K, V]], right: V): GenMap[K, V] =
getFirst[GenMap[K, V]](col, _.exists(_._2 == right))
def getFirstNotContainValue[K, V](col: GenTraversable[GenMap[K, V]], right: V): GenMap[K, V] =
getFirst[GenMap[K, V]](col, !_.exists(_._2 == right))
import scala.language.higherKinds
def getFirstJavaMapIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: Int = 0): java.util.Map[K, V] = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.isEmpty)
def getFirstJavaMapNotIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: Int = 0): java.util.Map[K, V] = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.isEmpty)
def getFirstJavaMapContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: K): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsKey(right))
def getFirstJavaMapNotContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: K): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsKey(right))
def getFirstJavaMapContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: V): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsValue(right))
def getFirstJavaMapNotContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: V): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsValue(right))
def getFirstJavaMapSizeEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: Int): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size == right)
def getFirstJavaMapSizeNotEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](col: java.util.Collection[JMAP[K, V]], right: Int): java.util.Map[K, V] =
getFirstInJavaCol[java.util.Map[K, V]](col.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size != right)
def getFirstJavaColSizeEqual[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: Int): java.util.Collection[T] =
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.size == right) // Safe cast, but ugly, can we do without it?
def getFirstJavaColSizeNotEqual[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: Int): java.util.Collection[T] =
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.size != right) // Safe cast, but ugly, can we do without it?
def getFirstJavaColContain[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: T): java.util.Collection[T] =
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.contains(right)) // Safe cast, but ugly, can we do without it?
def getFirstJavaColNotContain[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: T): java.util.Collection[T] =
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], !_.contains(right)) // Safe cast, but ugly, can we do without it?
def getFirstJavaColIsEmpty[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: Int = 0): java.util.Collection[T] = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.isEmpty) // Safe cast, but ugly, can we do without it?
def getFirstJavaColNotIsEmpty[T, C[t] <: java.util.Collection[_]](col: java.util.Collection[C[T]], right: Int = 0): java.util.Collection[T] = // right is not used, but to be consistent to other so that easier for code generation
getFirstInJavaCol[java.util.Collection[T]](col.asInstanceOf[java.util.Collection[java.util.Collection[T]]], !_.isEmpty) // Safe cast, but ugly, can we do without it?
def indexElement[T](itr: Iterator[T], xs: GenTraversable[T], errorFun: T => Boolean): Array[String] = {
val element = getNext[T](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: GenMap[_, _] => element.asInstanceOf[Tuple2[_, _]]._1
case genTrv: GenTraversable[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element))
}
def indexElementForJavaIterator[T](itr: java.util.Iterator[T], xs: java.util.Collection[T], errorFun: T => Boolean): Array[String] = {
val element = getNextInJavaIterator[T](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: java.util.Map[_, _] => element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
case genTrv: java.util.Collection[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element))
}
def indexElementForJavaIterator[K, V](itr: java.util.Iterator[java.util.Map.Entry[K, V]], xs: java.util.Map[K, V], errorFun: java.util.Map.Entry[K, V] => Boolean): Array[String] = {
val element = getNextInJavaIterator[java.util.Map.Entry[K, V]](itr, errorFun)
val indexOrKey = element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
Array(indexOrKey.toString, decorateToStringValue(element))
}
def indexLengthElement[T](itr: Iterator[String], xs: GenTraversable[String], errorFun: String => Boolean): Array[String] = {
val element = getNext[String](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: GenMap[_, _] => element.asInstanceOf[Tuple2[_, _]]._1
case genTrv: GenTraversable[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, element.length.toString, (if (element != null && element.isInstanceOf[Array[_]]) element.asInstanceOf[Array[T]].deep.toString else element.toString))
}
def indexLengthElement[T](itr: java.util.Iterator[String], xs: java.util.Collection[String], errorFun: String => Boolean): Array[String] = {
val element = getNextInJavaIterator[String](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: java.util.Map[_, _] => element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
case genTrv: java.util.Collection[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, element.length.toString, (if (element != null && element.isInstanceOf[Array[_]]) element.asInstanceOf[Array[T]].deep.toString else element.toString))
}
def indexElementLengthString[T](itr: Iterator[String], xs: GenTraversable[String], errorFun: String => Boolean): Array[String] = {
val element = getNext[String](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: GenMap[_, _] => element.asInstanceOf[Tuple2[_, _]]._1
case genTrv: GenTraversable[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.length.toString)
}
def indexElementLengthString[T](itr: java.util.Iterator[String], xs: java.util.Collection[String], errorFun: String => Boolean): Array[String] = {
val element = getNextInJavaIterator[String](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: java.util.Map[_, _] => element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
case genTrv: java.util.Collection[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.length.toString)
}
def indexElementLengthGenTraversable[T](itr: Iterator[GenTraversable[T]], xs: GenTraversable[GenTraversable[T]], errorFun: GenTraversable[T] => Boolean): Array[String] = {
val element = getNext[GenTraversable[T]](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: GenMap[_, _] => element.asInstanceOf[Tuple2[_, _]]._1
case genTrv: GenTraversable[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.size.toString)
}
def indexElementLengthArray[T](itr: Iterator[Array[T]], xs: GenTraversable[Array[T]], errorFun: Array[T] => Boolean): Array[String] = {
val element = getNext[Array[T]](itr, errorFun)
val indexOrKey: Any =
xs match {
case map: GenMap[_, _] => element.asInstanceOf[Tuple2[_, _]]._1
case genTrv: GenTraversable[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.size.toString)
}
def indexElementLengthJavaCol[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], errorFun: java.util.Collection[T] => Boolean): Array[String] = {
val element = getNextInJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], errorFun)
val indexOrKey: Any =
xs match {
case map: java.util.Map[_, _] => element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
case genTrv: java.util.Collection[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.size.toString)
}
def indexElementLengthJavaMap[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[java.util.Map[K, V]], errorFun: java.util.Map[K, V] => Boolean): Array[String] = {
val element = getNextInJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], errorFun)
val indexOrKey: Any =
xs match {
case map: java.util.Map[_, _] => element.asInstanceOf[java.util.Map.Entry[_, _]].getKey
case genTrv: java.util.Collection[_] => getIndex(xs, element)
}
Array(indexOrKey.toString, decorateToStringValue(element), element.size.toString)
}
def indexElementEqual[T](itr: Iterator[T], xs: GenTraversable[T], right: T): Array[String] =
indexElement[T](itr, xs, _ == right)
def indexElementNotEqual[T](itr: Iterator[T], xs: GenTraversable[T], right: T): Array[String] =
indexElement[T](itr, xs, _ != right)
def indexElementMoreThan(itr: Iterator[Int], xs: GenTraversable[Int], right: Int): Array[String] =
indexElement[Int](itr, xs, _ > right)
def indexElementMoreThanEqual(itr: Iterator[Int], xs: GenTraversable[Int], right: Int): Array[String] =
indexElement[Int](itr, xs, _ >= right)
def indexElementLessThan(itr: Iterator[Int], xs: GenTraversable[Int], right: Int): Array[String] =
indexElement[Int](itr, xs, _ < right)
def indexElementLessThanEqual(itr: Iterator[Int], xs: GenTraversable[Int], right: Int): Array[String] =
indexElement[Int](itr, xs, _ <= right)
def indexElementIsEmpty(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElement[String](itr, xs, _.isEmpty)
def indexElementIsNotEmpty(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElement[String](itr, xs, !_.isEmpty)
def indexElementLengthEqual(itr: Iterator[String], xs: GenTraversable[String], right: Int): Array[String] =
indexElement[String](itr, xs, _.length == right)
def indexElementLengthNotEqual(itr: Iterator[String], xs: GenTraversable[String], right: Int): Array[String] =
indexElementLengthString[String](itr, xs, (e: String) => e.length != right)
def indexElementSizeEqual(itr: Iterator[String], xs: GenTraversable[String], right: Int): Array[String] =
indexElement[String](itr, xs, _.size == right)
def indexElementSizeNotEqual(itr: Iterator[String], xs: GenTraversable[String], right: Int): Array[String] =
indexElementLengthString[String](itr, xs, (e: String) => e.size != right)
def indexElementLengthNotEqualLength(itr: Iterator[String], xs: GenTraversable[String], right: Int): Array[String] =
indexLengthElement[String](itr, xs, (e: String) => e.length != right)
def indexElementStartsWith(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, _.startsWith(right))
def indexElementNotStartsWith(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, !_.startsWith(right))
def indexElementEndsWith(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, _.endsWith(right))
def indexElementNotEndsWith(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, !_.endsWith(right))
def indexElementInclude(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, _.indexOf(right) >= 0)
def indexElementNotInclude(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, _.indexOf(right) < 0)
def indexElementMatches(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, _.matches(right))
def indexElementNotMatches(itr: Iterator[String], xs: GenTraversable[String], right: String): Array[String] =
indexElement[String](itr, xs, !_.matches(right))
//##################################
def javaMapEntry[K, V](key: K, value: V): java.util.Map.Entry[K, V] = org.scalactic.Entry(key, value)
def indexElementEqual[K, V](itr: java.util.Iterator[java.util.Map.Entry[K, V]], xs: java.util.Map[K, V], right: java.util.Map.Entry[K, V]): Array[String] =
indexElementForJavaIterator[K, V](itr, xs, (e: java.util.Map.Entry[K, V]) => e.getKey == right.getKey && e.getValue == right.getValue)
def indexElementNotEqual[K, V](itr: java.util.Iterator[java.util.Map.Entry[K, V]], xs: java.util.Map[K, V], right: java.util.Map.Entry[K, V]): Array[String] =
indexElementForJavaIterator[K, V](itr, xs, (e: java.util.Map.Entry[K, V]) => e.getKey != right.getKey || e.getValue != right.getValue)
def indexElementEqual[T](itr: java.util.Iterator[T], xs: java.util.Collection[T], right: T): Array[String] =
indexElementForJavaIterator[T](itr, xs, _ == right)
def indexElementNotEqual[T](itr: java.util.Iterator[T], xs: java.util.Collection[T], right: T): Array[String] =
indexElementForJavaIterator[T](itr, xs, _ != right)
def indexElementMoreThan(itr: java.util.Iterator[Int], xs: java.util.Collection[Int], right: Int): Array[String] =
indexElementForJavaIterator[Int](itr, xs, _ > right)
def indexElementMoreThanEqual(itr: java.util.Iterator[Int], xs: java.util.Collection[Int], right: Int): Array[String] =
indexElementForJavaIterator[Int](itr, xs, _ >= right)
def indexElementLessThan(itr: java.util.Iterator[Int], xs: java.util.Collection[Int], right: Int): Array[String] =
indexElementForJavaIterator[Int](itr, xs, _ < right)
def indexElementLessThanEqual(itr: java.util.Iterator[Int], xs: java.util.Collection[Int], right: Int): Array[String] =
indexElementForJavaIterator[Int](itr, xs, _ <= right)
def indexElementIsEmpty(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[String](itr, xs, _.isEmpty)
def indexElementIsNotEmpty(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[String](itr, xs, !_.isEmpty)
def indexElementLengthEqual(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: Int): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.length == right)
def indexElementLengthNotEqual(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: Int): Array[String] =
indexElementLengthString[String](itr, xs, (e: String) => e.length != right)
def indexElementSizeEqual(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: Int): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.size == right)
def indexElementSizeNotEqual(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: Int): Array[String] =
indexElementLengthString[String](itr, xs, (e: String) => e.size != right)
def indexElementLengthNotEqualLength(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: Int): Array[String] =
indexLengthElement[String](itr, xs, (e: String) => e.length != right)
def indexElementStartsWith(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.startsWith(right))
def indexElementNotStartsWith(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, !_.startsWith(right))
def indexElementEndsWith(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.endsWith(right))
def indexElementNotEndsWith(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, !_.endsWith(right))
def indexElementInclude(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.indexOf(right) >= 0)
def indexElementNotInclude(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.indexOf(right) < 0)
def indexElementMatches(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, _.matches(right))
def indexElementNotMatches(itr: java.util.Iterator[String], xs: java.util.Collection[String], right: String): Array[String] =
indexElementForJavaIterator[String](itr, xs, !_.matches(right))
//##################################
def indexElementSizeEqualGenTraversable[T](itr: Iterator[GenTraversable[T]], xs: GenTraversable[GenTraversable[T]], right: Int): Array[String] =
indexElement[GenTraversable[T]](itr, xs, _.size == right)
def indexElementSizeNotEqualGenTraversable[T](itr: Iterator[GenTraversable[T]], xs: GenTraversable[GenTraversable[T]], right: Int): Array[String] =
indexElementLengthGenTraversable[T](itr, xs, _.size != right)
def indexElementSizeEqualGenTraversableArray[T](itr: Iterator[Array[T]], xs: GenTraversable[Array[T]], right: Int): Array[T] =
indexElement[Array[T]](itr, xs, _.size == right).asInstanceOf[Array[T]]
def indexElementSizeNotEqualGenTraversableArray[T](itr: Iterator[Array[T]], xs: GenTraversable[Array[T]], right: Int): Array[T] =
indexElementLengthArray[T](itr, xs, _.size != right).asInstanceOf[Array[T]]
def indexElementContainGenTraversable[T](itr: Iterator[GenTraversable[T]], xs: GenTraversable[GenTraversable[T]], right: T): Array[String] =
indexElement[GenTraversable[T]](itr, xs, _.exists(_ == right))
def indexElementNotContainGenTraversable[T](itr: Iterator[GenTraversable[T]], xs: GenTraversable[GenTraversable[T]], right: T): Array[String] =
indexElement[GenTraversable[T]](itr, xs, !_.exists(_ == right))
def indexElementContainGenTraversableArray[T](itr: Iterator[Array[T]], xs: GenTraversable[Array[T]], right: T): Array[T] =
indexElement[Array[T]](itr, xs, _.exists(_ == right)).asInstanceOf[Array[T]]
def indexElementNotContainGenTraversableArray[T](itr: Iterator[Array[T]], xs: GenTraversable[Array[T]], right: T): Array[T] =
indexElement[Array[T]](itr, xs, !_.exists(_ == right)).asInstanceOf[Array[T]]
def indexElementRefEqual[T <: AnyRef](itr: Iterator[T], xs: GenTraversable[T], right: T): Array[String] =
indexElement[T](itr, xs, _ eq right)
def indexElementNotRefEqual[T <: AnyRef](itr: Iterator[T], xs: GenTraversable[T], right: T): Array[String] =
indexElement[T](itr, xs, _ ne right)
def indexElementRefEqual[T <: AnyRef](itr: java.util.Iterator[T], xs: java.util.Collection[T], right: T): Array[String] =
indexElementForJavaIterator[T](itr, xs, _ eq right)
def indexElementNotRefEqual[T <: AnyRef](itr: java.util.Iterator[T], xs: java.util.Collection[T], right: T): Array[String] =
indexElementForJavaIterator[T](itr, xs, _ ne right)
def indexElementContainKey[K, V](itr: Iterator[GenMap[K, V]], xs: GenTraversable[GenMap[K, V]], right: K): Array[String] =
indexElement[GenMap[K, V]](itr, xs, _.exists(_._1 == right))
def indexElementNotContainKey[K, V](itr: Iterator[GenMap[K, V]], xs: GenTraversable[GenMap[K, V]], right: K): Array[String] =
indexElement[GenMap[K, V]](itr, xs, !_.exists(_._1 == right))
def indexElementContainValue[K, V](itr: Iterator[GenMap[K, V]], xs: GenTraversable[GenMap[K, V]], right: V): Array[String] =
indexElement[GenMap[K, V]](itr, xs, _.exists(_._2 == right))
def indexElementNotContainValue[K, V](itr: Iterator[GenMap[K, V]], xs: GenTraversable[GenMap[K, V]], right: V): Array[String] =
indexElement[GenMap[K, V]](itr, xs, !_.exists(_._2 == right))
def indexElementJavaMapIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: Int = 0): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.isEmpty)
def indexElementJavaMapNotIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: Int = 0): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.isEmpty)
def indexElementJavaMapContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: K): Array[String] =
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsKey(right))
def indexElementJavaMapNotContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: K): Array[String] =
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsKey(right))
def indexElementJavaMapContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: V): Array[String] =
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsValue(right))
def indexElementJavaMapNotContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: V): Array[String] =
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsValue(right))
def indexElementJavaMapSizeEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: Int): Array[String] =
indexElementForJavaIterator[java.util.Map[K, V]](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size == right)
def indexElementJavaMapSizeNotEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](itr: java.util.Iterator[JMAP[K, V]], xs: java.util.Collection[JMAP[K, V]], right: Int): Array[String] =
indexElementLengthJavaMap[K, V, java.util.Map](itr.asInstanceOf[java.util.Iterator[java.util.Map[K, V]]], xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size != right)
def indexElementJavaColSizeEqual[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: Int): Array[String] =
indexElementForJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.size == right)
def indexElementJavaColSizeNotEqual[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: Int): Array[String] =
indexElementLengthJavaCol[T, java.util.Collection](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.size != right)
def indexElementJavaColContain[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: T): Array[String] =
indexElementForJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.contains(right))
def indexElementJavaColNotContain[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: T): Array[String] =
indexElementForJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], !_.contains(right))
def indexElementJavaColIsEmpty[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: Int = 0): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], _.isEmpty)
def indexElementJavaColNotIsEmpty[T, C[t] <: java.util.Collection[_]](itr: java.util.Iterator[C[T]], xs: java.util.Collection[C[T]], right: Int = 0): Array[String] = // right is not used, but to be consistent to other so that easier for code generation
indexElementForJavaIterator[java.util.Collection[T]](itr.asInstanceOf[java.util.Iterator[java.util.Collection[T]]], xs.asInstanceOf[java.util.Collection[java.util.Collection[T]]], !_.isEmpty)
private def succeededIndexes[T](xs: GenTraversable[T], filterFun: T => Boolean): String = {
xs match {
case map: GenMap[_, _] =>
val passedList = map.toList.filter(e => filterFun(e)).map(_._1).toList
if (passedList.size > 1)
"key " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"key " + passedList.last.toString
else
""
case _ =>
val passedList = getIndexes(xs, xs.toList.filter(e => filterFun(e))).toList
if (passedList.size > 1)
"index " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"index " + passedList.last.toString
else
""
}
}
private def succeededIndexesInJavaCol[T](xs: java.util.Collection[T], filterFun: T => Boolean): String = {
import collection.JavaConverters._
val passedList = getIndexes(xs.asScala, xs.asScala.toList.filter(e => filterFun(e))).toList
if (passedList.size > 1)
"index " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"index " + passedList.last.toString
else
""
}
private def succeededIndexesInJavaMap[K, V](xs: java.util.Map[K, V], filterFun: java.util.Map.Entry[K, V] => Boolean): String = {
import collection.JavaConverters._
val passedList = xs.asScala.toList.filter(e => filterFun(org.scalactic.Entry(e._1, e._2))).toList.map(_._1)
if (passedList.size > 1)
"key " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"key " + passedList.last.toString
else
""
}
private def failEarlySucceededIndexes[T](xs: GenTraversable[T], filterFun: T => Boolean, maxSucceed: Int): String = {
xs match {
case map: GenMap[_, _] =>
val passedList = map.toList.filter(e => filterFun(e)).take(maxSucceed).toList.map(_._1)
if (passedList.size > 1)
"key " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"key " + passedList.last.toString
else
""
case _ =>
val passedList = getIndexes(xs, xs.toList.filter(e => filterFun(e))).take(maxSucceed).toList
if (passedList.size > 1)
"index " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"index " + passedList.last.toString
else
""
}
}
private def failEarlySucceededIndexesInJavaCol[T](xs: java.util.Collection[T], filterFun: T => Boolean, maxSucceed: Int): String = {
import collection.JavaConverters._
val passedList = getIndexes(xs.asScala, xs.asScala.toList.filter(e => filterFun(e))).take(maxSucceed).toList
if (passedList.size > 1)
"index " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"index " + passedList.last.toString
else
""
}
private def failEarlySucceededIndexesInJavaMap[K, V](xs: java.util.Map[K, V], filterFun: java.util.Map.Entry[K, V] => Boolean, maxSucceed: Int): String = {
import collection.JavaConverters._
val passedList = xs.asScala.toList.filter(e => filterFun(org.scalactic.Entry(e._1, e._2))).take(maxSucceed).toList.map(_._1)
if (passedList.size > 1)
"key " + passedList.dropRight(1).mkString(", ") + " and " + passedList.last
else if (passedList.size == 1)
"key " + passedList.last.toString
else
""
}
def succeededIndexesEqualBoolean[T](xs: GenTraversable[T], value: Boolean): String =
succeededIndexes(xs, (e: T) => value)
def succeededIndexesNotEqualBoolean[T](xs: GenTraversable[T], value: Boolean): String =
succeededIndexes(xs, (e: T) => !value)
def succeededIndexesEqual[T](xs: GenTraversable[T], value: T): String =
succeededIndexes(xs, (e: T) => e == value)
def succeededIndexesNotEqual[T](xs: GenTraversable[T], value: T): String =
succeededIndexes(xs, (e: T) => e != value)
def succeededIndexesEqual[K, V](xs: java.util.Map[K, V], value: java.util.Map.Entry[K, V]): String =
succeededIndexesInJavaMap(xs, (e: java.util.Map.Entry[K, V]) => e.getKey == value.getKey && e.getValue == value.getValue)
def succeededIndexesNotEqual[K, V](xs: java.util.Map[K, V], value: java.util.Map.Entry[K, V]): String =
succeededIndexesInJavaMap(xs, (e: java.util.Map.Entry[K, V]) => e.getKey != value.getKey || e.getValue != value.getValue)
def succeededIndexesLessThanEqual(xs: GenTraversable[Int], value: Int): String =
succeededIndexes(xs, (e: Int) => e <= value)
def succeededIndexesLessThan(xs: GenTraversable[Int], value: Int): String =
succeededIndexes(xs, (e: Int) => e < value)
def succeededIndexesMoreThanEqual(xs: GenTraversable[Int], value: Int): String =
succeededIndexes(xs, (e: Int) => e >= value)
def succeededIndexesMoreThan(xs: GenTraversable[Int], value: Int): String =
succeededIndexes(xs, (e: Int) => e > value)
def succeededIndexesIsEmpty(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.isEmpty)
def succeededIndexesIsNotEmpty(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => !e.isEmpty)
def succeededIndexesSizeEqual(xs: GenTraversable[String], value: Int): String =
succeededIndexes(xs, (e: String) => e.size == value)
def succeededIndexesSizeNotEqual(xs: GenTraversable[String], value: Int): String =
succeededIndexes(xs, (e: String) => e.size != value)
def succeededIndexesLengthEqual(xs: GenTraversable[String], value: Int): String =
succeededIndexes(xs, (e: String) => e.length == value)
def succeededIndexesLengthNotEqual(xs: GenTraversable[String], value: Int): String =
succeededIndexes(xs, (e: String) => e.length != value)
def succeededIndexesStartsWith(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.startsWith(value))
def succeededIndexesNotStartsWith(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => !e.startsWith(value))
def succeededIndexesEndsWith(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.endsWith(value))
def succeededIndexesNotEndsWith(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => !e.endsWith(value))
def succeededIndexesInclude(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.indexOf(value) >= 0)
def succeededIndexesNotInclude(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.indexOf(value) < 0)
def succeededIndexesSizeEqualGenTraversable[T](xs: GenTraversable[GenTraversable[T]], value: Int): String =
succeededIndexes(xs, (e: GenTraversable[T]) => e.size == value)
def succeededIndexesSizeNotEqualGenTraversable[T](xs: GenTraversable[GenTraversable[T]], value: Int): String =
succeededIndexes(xs, (e: GenTraversable[T]) => e.size != value)
def succeededIndexesSizeEqualGenTraversableArray[T](xs: GenTraversable[Array[T]], value: Int): String =
succeededIndexes(xs, (e: Array[T]) => e.size == value)
def succeededIndexesSizeNotEqualGenTraversableArray[T](xs: GenTraversable[Array[T]], value: Int): String =
succeededIndexes(xs, (e: Array[T]) => e.size != value)
def succeededIndexesMatches(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => e.matches(value))
def succeededIndexesNotMatches(xs: GenTraversable[String], value: String): String =
succeededIndexes(xs, (e: String) => !e.matches(value))
def succeededIndexesEqualBoolean[T](xs: java.util.Collection[T], value: Boolean): String =
succeededIndexesInJavaCol(xs, (e: T) => value)
def succeededIndexesNotEqualBoolean[T](xs: java.util.Collection[T], value: Boolean): String =
succeededIndexesInJavaCol(xs, (e: T) => !value)
def succeededIndexesEqual[T](xs: java.util.Collection[T], value: T): String =
succeededIndexesInJavaCol(xs, (e: T) => e == value)
def succeededIndexesNotEqual[T](xs: java.util.Collection[T], value: T): String =
succeededIndexesInJavaCol(xs, (e: T) => e != value)
def succeededIndexesLessThanEqual(xs: java.util.Collection[Int], value: Int): String =
succeededIndexesInJavaCol(xs, (e: Int) => e <= value)
def succeededIndexesLessThan(xs: java.util.Collection[Int], value: Int): String =
succeededIndexesInJavaCol(xs, (e: Int) => e < value)
def succeededIndexesMoreThanEqual(xs: java.util.Collection[Int], value: Int): String =
succeededIndexesInJavaCol(xs, (e: Int) => e >= value)
def succeededIndexesMoreThan(xs: java.util.Collection[Int], value: Int): String =
succeededIndexesInJavaCol(xs, (e: Int) => e > value)
def succeededIndexesIsEmpty(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.isEmpty)
def succeededIndexesIsNotEmpty(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => !e.isEmpty)
def succeededIndexesSizeEqual(xs: java.util.Collection[String], value: Int): String =
succeededIndexesInJavaCol(xs, (e: String) => e.size == value)
def succeededIndexesSizeNotEqual(xs: java.util.Collection[String], value: Int): String =
succeededIndexesInJavaCol(xs, (e: String) => e.size != value)
def succeededIndexesLengthEqual(xs: java.util.Collection[String], value: Int): String =
succeededIndexesInJavaCol(xs, (e: String) => e.length == value)
def succeededIndexesLengthNotEqual(xs: java.util.Collection[String], value: Int): String =
succeededIndexesInJavaCol(xs, (e: String) => e.length != value)
def succeededIndexesStartsWith(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.startsWith(value))
def succeededIndexesNotStartsWith(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => !e.startsWith(value))
def succeededIndexesEndsWith(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.endsWith(value))
def succeededIndexesNotEndsWith(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => !e.endsWith(value))
def succeededIndexesInclude(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.indexOf(value) >= 0)
def succeededIndexesNotInclude(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.indexOf(value) < 0)
def succeededIndexesMatches(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => e.matches(value))
def succeededIndexesNotMatches(xs: java.util.Collection[String], value: String): String =
succeededIndexesInJavaCol(xs, (e: String) => !e.matches(value))
def succeededIndexesContainGenTraversable[T](xs: GenTraversable[GenTraversable[T]], right: T): String =
succeededIndexes[GenTraversable[T]](xs, _.exists(_ == right))
def succeededIndexesNotContainGenTraversable[T](xs: GenTraversable[GenTraversable[T]], right: T): String =
succeededIndexes[GenTraversable[T]](xs, !_.exists(_ == right))
def succeededIndexesContainGenTraversableArray[T](xs: GenTraversable[Array[T]], right: T): String =
succeededIndexes[Array[T]](xs, _.exists(_ == right))
def succeededIndexesNotContainGenTraversableArray[T](xs: GenTraversable[Array[T]], right: T): String =
succeededIndexes[Array[T]](xs, !_.exists(_ == right))
def succeededIndexesRefEqual[T <: AnyRef](xs: GenTraversable[T], value: T): String =
succeededIndexes[T](xs, _ eq value)
def succeededIndexesNotRefEqual[T <: AnyRef](xs: GenTraversable[T], value: T): String =
succeededIndexes[T](xs, _ ne value)
//#################################
def succeededIndexesRefEqual[T <: AnyRef](xs: java.util.Collection[T], value: T): String =
succeededIndexesInJavaCol[T](xs, _ eq value)
def succeededIndexesNotRefEqual[T <: AnyRef](xs: java.util.Collection[T], value: T): String =
succeededIndexesInJavaCol[T](xs, _ ne value)
//#################################
def succeededIndexesContainKey[K, V](xs: GenTraversable[GenMap[K, V]], right: K): String =
succeededIndexes[GenMap[K, V]](xs, _.exists(_._1 == right))
def succeededIndexesNotContainKey[K, V](xs: GenTraversable[GenMap[K, V]], right: K): String =
succeededIndexes[GenMap[K, V]](xs, !_.exists(_._1 == right))
def succeededIndexesContainValue[K, V](xs: GenTraversable[GenMap[K, V]], right: V): String =
succeededIndexes[GenMap[K, V]](xs, _.exists(_._2 == right))
def succeededIndexesNotContainValue[K, V](xs: GenTraversable[GenMap[K, V]], right: V): String =
succeededIndexes[GenMap[K, V]](xs, !_.exists(_._2 == right))
def succeededIndexesJavaMapIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int = 0): String = // right is not used, but to be consistent to other so that easier for code generation
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.isEmpty)
def succeededIndexesJavaMapNotIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int = 0): String = // right is not used, but to be consistent to other so that easier for code generation
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.isEmpty)
def succeededIndexesJavaMapContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: K): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsKey(right))
def succeededIndexesJavaMapNotContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: K): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsKey(right))
def succeededIndexesJavaMapContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: V): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsValue(right))
def succeededIndexesJavaMapNotContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: V): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsValue(right))
def succeededIndexesJavaMapSizeEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size == right)
def succeededIndexesJavaMapSizeNotEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int): String =
succeededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size != right)
def succeededIndexesJavaColSizeEqual[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int): String =
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.size == right)
def succeededIndexesJavaColSizeNotEqual[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int): String =
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.size != right)
def succeededIndexesJavaColContain[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: E): String =
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.contains(right))
def succeededIndexesJavaColNotContain[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: E): String =
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], !_.contains(right))
def succeededIndexesJavaColIsEmpty[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int = 0): String = // right is not used, but to be consistent to other so that easier for code generation
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.isEmpty)
def succeededIndexesJavaColNotIsEmpty[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int = 0): String = // right is not used, but to be consistent to other so that easier for code generation
succeededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], !_.isEmpty)
def failEarlySucceededIndexesEqualBoolean[T](xs: GenTraversable[T], value: Boolean, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: T) => value, maxSucceed)
def failEarlySucceededIndexesNotEqualBoolean[T](xs: GenTraversable[T], value: Boolean, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: T) => !value, maxSucceed)
def failEarlySucceededIndexesEqual[T](xs: GenTraversable[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: T) => e == value, maxSucceed)
def failEarlySucceededIndexesNotEqual[T](xs: GenTraversable[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: T) => e != value, maxSucceed)
def failEarlySucceededIndexesLessThanEqual(xs: GenTraversable[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Int) => e <= value, maxSucceed)
def failEarlySucceededIndexesLessThan(xs: GenTraversable[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Int) => e < value, maxSucceed)
def failEarlySucceededIndexesMoreThanEqual(xs: GenTraversable[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Int) => e >= value, maxSucceed)
def failEarlySucceededIndexesMoreThan(xs: GenTraversable[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Int) => e > value, maxSucceed)
def failEarlySucceededIndexesIsEmpty(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.isEmpty, maxSucceed)
def failEarlySucceededIndexesIsNotEmpty(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => !e.isEmpty, maxSucceed)
def failEarlySucceededIndexesSizeEqual(xs: GenTraversable[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.size == value, maxSucceed)
def failEarlySucceededIndexesSizeNotEqual(xs: GenTraversable[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.size != value, maxSucceed)
def failEarlySucceededIndexesLengthEqual(xs: GenTraversable[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.length == value, maxSucceed)
def failEarlySucceededIndexesLengthNotEqual(xs: GenTraversable[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.length != value, maxSucceed)
def failEarlySucceededIndexesStartsWith(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.startsWith(value), maxSucceed)
def failEarlySucceededIndexesNotStartsWith(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => !e.startsWith(value), maxSucceed)
def failEarlySucceededIndexesEndsWith(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.endsWith(value), maxSucceed)
def failEarlySucceededIndexesNotEndsWith(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => !e.endsWith(value), maxSucceed)
def failEarlySucceededIndexesInclude(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.indexOf(value) >= 0, maxSucceed)
def failEarlySucceededIndexesNotInclude(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.indexOf(value) < 0, maxSucceed)
//################################################
def failEarlySucceededIndexesEqualBoolean[T](xs: java.util.Collection[T], value: Boolean, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: T) => value, maxSucceed)
def failEarlySucceededIndexesNotEqualBoolean[T](xs: java.util.Collection[T], value: Boolean, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: T) => !value, maxSucceed)
def failEarlySucceededIndexesEqual[T](xs: java.util.Collection[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: T) => e == value, maxSucceed)
def failEarlySucceededIndexesNotEqual[T](xs: java.util.Collection[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: T) => e != value, maxSucceed)
def failEarlySucceededIndexesEqual[K, V](xs: java.util.Map[K, V], value: java.util.Map.Entry[K, V], maxSucceed: Int): String =
failEarlySucceededIndexesInJavaMap(xs, (e: java.util.Map.Entry[K, V]) => e.getKey == value.getKey && e.getValue == value.getValue, maxSucceed)
def failEarlySucceededIndexesNotEqual[K, V](xs: java.util.Map[K, V], value: java.util.Map.Entry[K, V], maxSucceed: Int): String =
failEarlySucceededIndexesInJavaMap(xs, (e: java.util.Map.Entry[K, V]) => e.getKey != value.getKey || e.getValue != value.getValue, maxSucceed)
def failEarlySucceededIndexesLessThanEqual(xs: java.util.Collection[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: Int) => e <= value, maxSucceed)
def failEarlySucceededIndexesLessThan(xs: java.util.Collection[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: Int) => e < value, maxSucceed)
def failEarlySucceededIndexesMoreThanEqual(xs: java.util.Collection[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: Int) => e >= value, maxSucceed)
def failEarlySucceededIndexesMoreThan(xs: java.util.Collection[Int], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: Int) => e > value, maxSucceed)
def failEarlySucceededIndexesIsEmpty(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.isEmpty, maxSucceed)
def failEarlySucceededIndexesIsNotEmpty(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => !e.isEmpty, maxSucceed)
def failEarlySucceededIndexesSizeEqual(xs: java.util.Collection[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.size == value, maxSucceed)
def failEarlySucceededIndexesSizeNotEqual(xs: java.util.Collection[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.size != value, maxSucceed)
def failEarlySucceededIndexesLengthEqual(xs: java.util.Collection[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.length == value, maxSucceed)
def failEarlySucceededIndexesLengthNotEqual(xs: java.util.Collection[String], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.length != value, maxSucceed)
def failEarlySucceededIndexesStartsWith(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.startsWith(value), maxSucceed)
def failEarlySucceededIndexesNotStartsWith(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => !e.startsWith(value), maxSucceed)
def failEarlySucceededIndexesEndsWith(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.endsWith(value), maxSucceed)
def failEarlySucceededIndexesNotEndsWith(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => !e.endsWith(value), maxSucceed)
def failEarlySucceededIndexesInclude(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.indexOf(value) >= 0, maxSucceed)
def failEarlySucceededIndexesNotInclude(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.indexOf(value) < 0, maxSucceed)
//################################################
def failEarlySucceededIndexesSizeEqualGenTraversable[T](xs: GenTraversable[GenTraversable[T]], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes[GenTraversable[T]](xs, _.size == value, maxSucceed)
def failEarlySucceededIndexesSizeNotEqualGenTraversable[T](xs: GenTraversable[GenTraversable[T]], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes[GenTraversable[T]](xs, _.size != value, maxSucceed)
def failEarlySucceededIndexesSizeEqualGenTraversableArray[T](xs: GenTraversable[Array[T]], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Array[T]) => e.size == value, maxSucceed)
def failEarlySucceededIndexesSizeNotEqualGenTraversableArray[T](xs: GenTraversable[Array[T]], value: Int, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: Array[T]) => e.size != value, maxSucceed)
def failEarlySucceededIndexesMatches(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => e.matches(value), maxSucceed)
def failEarlySucceededIndexesNotMatches(xs: GenTraversable[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexes(xs, (e: String) => !e.matches(value), maxSucceed)
def failEarlySucceededIndexesMatches(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => e.matches(value), maxSucceed)
def failEarlySucceededIndexesNotMatches(xs: java.util.Collection[String], value: String, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol(xs, (e: String) => !e.matches(value), maxSucceed)
def failEarlySucceededIndexesContainGenTraversable[T](xs: GenTraversable[GenTraversable[T]], right: T, maxSucceed: Int): String =
failEarlySucceededIndexes[GenTraversable[T]](xs, _.exists(_ == right), maxSucceed)
def failEarlySucceededIndexesNotContainGenTraversable[T](xs: GenTraversable[GenTraversable[T]], right: T, maxSucceed: Int): String =
failEarlySucceededIndexes[GenTraversable[T]](xs, !_.exists(_ == right), maxSucceed)
def failEarlySucceededIndexesContainGenTraversableArray[T](xs: GenTraversable[Array[T]], right: T, maxSucceed: Int): String =
failEarlySucceededIndexes[Array[T]](xs, _.exists(_ == right), maxSucceed)
def failEarlySucceededIndexesNotContainGenTraversableArray[T](xs: GenTraversable[Array[T]], right: T, maxSucceed: Int): String =
failEarlySucceededIndexes[Array[T]](xs, !_.exists(_ == right), maxSucceed)
def failEarlySucceededIndexesRefEqual[T <: AnyRef](xs: GenTraversable[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexes[T](xs, _ eq value, maxSucceed)
def failEarlySucceededIndexesNotRefEqual[T <: AnyRef](xs: GenTraversable[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexes[T](xs, _ ne value, maxSucceed)
def failEarlySucceededIndexesRefEqual[T <: AnyRef](xs: java.util.Collection[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[T](xs, _ eq value, maxSucceed)
def failEarlySucceededIndexesNotRefEqual[T <: AnyRef](xs: java.util.Collection[T], value: T, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[T](xs, _ ne value, maxSucceed)
def failEarlySucceededIndexesContainKey[K, V](xs: GenTraversable[GenMap[K, V]], right: K, maxSucceed: Int): String =
failEarlySucceededIndexes[GenMap[K, V]](xs, _.exists(_._1 == right), maxSucceed)
def failEarlySucceededIndexesNotContainKey[K, V](xs: GenTraversable[GenMap[K, V]], right: K, maxSucceed: Int): String =
failEarlySucceededIndexes[GenMap[K, V]](xs, !_.exists(_._1 == right), maxSucceed)
def failEarlySucceededIndexesContainValue[K, V](xs: GenTraversable[GenMap[K, V]], right: V, maxSucceed: Int): String =
failEarlySucceededIndexes[GenMap[K, V]](xs, _.exists(_._2 == right), maxSucceed)
def failEarlySucceededIndexesNotContainValue[K, V](xs: GenTraversable[GenMap[K, V]], right: V, maxSucceed: Int): String =
failEarlySucceededIndexes[GenMap[K, V]](xs, !_.exists(_._2 == right), maxSucceed)
def failEarlySucceededIndexesJavaMapIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int = 0, maxSucceed: Int): String = // right is not used, but to be consistent to other so that easier for code generation
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.isEmpty, maxSucceed)
def failEarlySucceededIndexesJavaMapNotIsEmpty[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int = 0, maxSucceed: Int): String = // right is not used, but to be consistent to other so that easier for code generation
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.isEmpty, maxSucceed)
def failEarlySucceededIndexesJavaMapContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: K, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsKey(right), maxSucceed)
def failEarlySucceededIndexesJavaMapNotContainKey[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: K, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsKey(right), maxSucceed)
def failEarlySucceededIndexesJavaMapContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: V, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.containsValue(right), maxSucceed)
def failEarlySucceededIndexesJavaMapNotContainValue[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: V, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], !_.containsValue(right), maxSucceed)
def failEarlySucceededIndexesJavaMapSizeEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size == right, maxSucceed)
def failEarlySucceededIndexesJavaMapSizeNotEqual[K, V, JMAP[k, v] <: java.util.Map[_, _]](xs: java.util.Collection[JMAP[K, V]], right: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Map[K, V]](xs.asInstanceOf[java.util.Collection[java.util.Map[K, V]]], _.size != right, maxSucceed)
def failEarlySucceededIndexesJavaColSizeEqual[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.size == right, maxSucceed)
def failEarlySucceededIndexesJavaColSizeNotEqual[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.size != right, maxSucceed)
def failEarlySucceededIndexesJavaColContain[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: E, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.contains(right), maxSucceed)
def failEarlySucceededIndexesJavaColNotContain[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: E, maxSucceed: Int): String =
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], !_.contains(right), maxSucceed)
def failEarlySucceededIndexesJavaColIsEmpty[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int = 0, maxSucceed: Int): String = // right is not used, but to be consistent to other so that easier for code generation
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], _.isEmpty, maxSucceed)
def failEarlySucceededIndexesJavaColNotIsEmpty[E, C[e] <: java.util.Collection[_]](xs: java.util.Collection[C[E]], right: Int = 0, maxSucceed: Int): String = // right is not used, but to be consistent to other so that easier for code generation
failEarlySucceededIndexesInJavaCol[java.util.Collection[E]](xs.asInstanceOf[java.util.Collection[java.util.Collection[E]]], !_.isEmpty, maxSucceed)
private val TEMP_DIR_ATTEMPTS = 10000
// This is based on createTempDir here (Apache License): http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/io/Files.java
// java.nio.file.Files#createTempDirectory() exists in Java 7 should be preferred when we no longer support Java 5/6.
def createTempDirectory(): File = {
val baseDir = new File(System.getProperty("java.io.tmpdir"))
val baseName = System.currentTimeMillis + "-"
@tailrec
def tryCreateTempDirectory(counter: Int): Option[File] = {
val tempDir = new File(baseDir, baseName + counter)
if (tempDir.mkdir())
Some(tempDir)
else if (counter < TEMP_DIR_ATTEMPTS)
tryCreateTempDirectory(counter + 1)
else
None
}
tryCreateTempDirectory(0) match {
case Some(tempDir) => tempDir
case None =>
throw new IllegalStateException(
"Failed to create directory within " +
TEMP_DIR_ATTEMPTS + " attempts (tried " +
baseName + "0 to " + baseName +
(TEMP_DIR_ATTEMPTS - 1) + ')');
}
}
def javaSet[T](elements: T*): java.util.Set[T] = {
val javaSet = new java.util.HashSet[T]()
elements.foreach(javaSet.add(_))
javaSet
}
def javaList[T](elements: T*): java.util.List[T] = {
val javaList = new java.util.ArrayList[T]()
elements.foreach(javaList.add(_))
javaList
}
def javaMap[K, V](elements: Entry[K, V]*): java.util.LinkedHashMap[K, V] = {
val m = new java.util.LinkedHashMap[K, V]
elements.foreach(e => m.put(e.getKey, e.getValue))
m
}
// This gives a comparator that compares based on the value in the passed in order map
private def orderMapComparator[T](orderMap: Map[T, Int]): java.util.Comparator[T] =
new java.util.Comparator[T] {
def compare(x: T, y: T): Int = {
// When both x and y is defined in order map, use its corresponding value to compare (which in usage below, is the index of the insertion order)
if (orderMap.get(x).isDefined && orderMap.get(y).isDefined)
orderMap(x) compare orderMap(y)
else {
// It can happens that the comparator is used by equal method to check if 2 element is equaled.
// In the use-case below, orderMap only contains elements within the TreeSet/TreeMap itself,
// but in equal method elements from other instances of TreeSet/TreeMap can be passed in to check
// for equality. So the below handles element of type Int and String, which is enough for our tests.
// hashCode will be used for other types of objects, in future, special care for other types can be added
// if necessary.
// The relationship and behavior of comparator/ordering/equals is quite well defined in JavaDoc of java.lang.Comparable here:
// http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html
x match {
case xInt: Int =>
y match {
case yInt: Int => xInt compare yInt
case _ => x.hashCode compare y.hashCode
}
case xStr: String =>
y match {
case yStr: String => xStr compare yStr
case _ => x.hashCode compare y.hashCode
}
case _ => x.hashCode compare y.hashCode
}
}
}
}
def sortedSet[T](elements: T*): SortedSet[T] = {
val orderMap = Map.empty[T, Int] ++ elements.zipWithIndex
val comparator = orderMapComparator(orderMap)
implicit val ordering = new Ordering[T] {
def compare(x: T, y: T): Int = comparator.compare(x, y)
}
SortedSet.empty[T] ++ elements
}
def sortedMap[K, V](elements: (K, V)*): SortedMap[K, V] = {
val orderMap = Map.empty[K, Int] ++ elements.map(_._1).zipWithIndex
val comparator = orderMapComparator(orderMap)
implicit val ordering = new Ordering[K] {
def compare(x: K, y: K): Int = comparator.compare(x, y)
}
SortedMap.empty[K, V] ++ elements
}
def javaSortedSet[T](elements: T*): java.util.SortedSet[T] = {
val orderMap = Map.empty[T, Int] ++ elements.zipWithIndex
val comparator = orderMapComparator(orderMap)
val sortedSet = new java.util.TreeSet[T](comparator)
elements.foreach(sortedSet.add(_))
sortedSet
}
def javaSortedMap[K, V](elements: Entry[K, V]*): java.util.SortedMap[K, V] = {
val orderMap = Map.empty[K, Int] ++ elements.map(_.getKey).zipWithIndex
val comparator = orderMapComparator(orderMap)
val sortedMap = new java.util.TreeMap[K, V](comparator)
elements.foreach(e => sortedMap.put(e.getKey, e.getValue))
sortedMap
}
def serializeRoundtrip[A](a: A): A = {
val baos = new java.io.ByteArrayOutputStream
val oos = new java.io.ObjectOutputStream(baos)
oos.writeObject(a)
oos.flush()
val ois = new java.io.ObjectInputStream(new java.io.ByteArrayInputStream(baos.toByteArray))
ois.readObject.asInstanceOf[A]
}
def checkMessageStackDepth(exception: StackDepthException, message: String, fileName: String, lineNumber: Int) {
assert(exception.message === Some(message))
assert(exception.failedCodeFileName === Some(fileName))
assert(exception.failedCodeLineNumber === Some(lineNumber))
}
def prettifyAst(str: String): String = {
import scala.annotation.tailrec
def getUntilNextDoubleQuote(itr: BufferedIterator[Char], buf: StringBuilder = new StringBuilder): String = {
if (itr.hasNext) {
val next = itr.next
buf.append(next)
if (next != '\"')
getUntilNextDoubleQuote(itr, buf)
else
buf.toString
}
else
throw new IllegalStateException("Expecting closing \", but none of them found")
}
val brackets = Set('(', ')')
@tailrec
def getNextBracket(itr: BufferedIterator[Char], buf: StringBuilder = new StringBuilder): (Char, String) = {
if (itr.hasNext) {
if (brackets.contains(itr.head))
(itr.head, buf.toString)
else {
val next = itr.next
buf.append(next)
if (next == '\"')
buf.append(getUntilNextDoubleQuote(itr))
getNextBracket(itr, buf)
}
}
else
throw new IllegalStateException("Expecting '(' or ')', but none of them found")
}
@tailrec
def transform(itr: BufferedIterator[Char], openBracket: Int, builder: StringBuilder, multilineBracket: Boolean = false) {
if (itr.hasNext) {
val next = itr.next
val (newOpenBracket, newMultilineBracket) =
next match {
case '(' =>
val (nextBracket, textWithin) = getNextBracket(itr)
if (nextBracket == '(') {
builder.append("(\n")
val newOpenBracket = openBracket + 1
builder.append(" " * newOpenBracket)
builder.append(textWithin)
(newOpenBracket, true)
}
else {
builder.append("(")
builder.append(textWithin)
(openBracket, false)
}
case ')' =>
val newOpenBracket =
if (multilineBracket) {
builder.append("\n")
val newOpenBracket =
if (openBracket > 0)
openBracket - 1
else
openBracket
builder.append(" " * newOpenBracket)
newOpenBracket
}
else
openBracket
if (itr.hasNext && itr.head == ',') {
itr.next
builder.append("),\n")
builder.append(" " * newOpenBracket)
}
else
builder.append(")")
if (itr.hasNext && itr.head == ' ')
itr.next
if (newOpenBracket == 0)
builder.append("\n")
(newOpenBracket, true)
case '\n' =>
builder.append("\n")
builder.append(" " * openBracket)
(openBracket, multilineBracket)
case other => builder.append(other)
(openBracket, multilineBracket)
}
transform(itr, newOpenBracket, builder, newMultilineBracket)
}
}
val itr = str.toCharArray.iterator.buffered
val builder = new StringBuilder
transform(itr, 0, builder)
builder.toString
}
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/fixture/ExampleFunSpec.scala | package test.fixture
import org.scalatest._
class ExampleFunSpec extends fixture.FunSpec {
type FixtureParam = String
def withFixture(test: OneArgTest): Outcome = {
test("hi")
}
describe("A Set") {
describe("when empty") {
it("should have size 0") { f =>
assert(Set.empty.size == 0)
}
it("should produce NoSuchElementException when head is invoked") { f =>
intercept[NoSuchElementException] {
Set.empty.head
}
}
}
}
} |
cquiroz/scalatest | scalactic-test/src/test/scala/org/scalactic/algebra/DistributiveSpec.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.algebra
import scala.language.higherKinds
import org.scalactic.UnitSpec
class DistributiveSpec extends UnitSpec {
// removing a list of elements is distributive over concatination
class ListRemoveDistributive[A] extends Distributive[List[A]] {
def op(a: List[A], b: List[A]): List[A] = a ++ b
def dop(as: List[A], bs: List[A]): List[A] = bs.filter(b => !as.contains(b))
}
// Int multiplication over addition is distributive
class IntMultiOverAdditionDistributive extends Distributive[Int] {
def op(a: Int, b: Int): Int = a + b
def dop(a: Int, b: Int): Int = a * b
}
"Removing a list of elemenents and concatination " should
"be distributive where remove is the distributive dop and concat is op which is distributed over " in {
implicit val dist = new ListRemoveDistributive[Int]
import Distributive.adapters
val as = List(1,2,3)
val bs = List(2,3,4,5)
val cs = List()
val op = dist.op _
val dop = dist.dop _
val fn: (Int => Int) = x => x + 1
(as dop (bs op cs)) shouldEqual ((as dop bs) op (as dop cs))
}
"Int multiplication over addition distributive " should
"have a binary operation 'op' and another binary operation (dop) that distributes over 'op'" in {
implicit val dist = new IntMultiOverAdditionDistributive
import Distributive.adapters
val a = 64
val b = 256
val c = 32
(a dop (b op c)) shouldEqual ((a dop b) op (a dop c))
}
}
|
cquiroz/scalatest | scalatest-test.js/src/test/scala/test/MasterTestSuite.scala | <filename>scalatest-test.js/src/test/scala/test/MasterTestSuite.scala
package test
import org.scalatest.{FunSuite, Suites}
class MasterTestSuite extends Suites(
new ASuite,
new BSuite,
new CSuite
)
protected[test] class ASuite extends FunSuite {
test("test A1") {
assert(true == true)
}
}
protected[test] class BSuite extends FunSuite {
test("test B1") {
assert(true == true)
}
}
protected[test] class CSuite extends FunSuite {
ignore("test C1") {
assert(true == true)
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/Notifier.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
/**
* Trait providing an <code>apply</code> method to which status updates about a running suite of tests can be reported.
*
* <p>
* An <code>Notifier</code> is essentially
* used to wrap a <code>Reporter</code> and provide easy ways to send status updates
* to that <code>Reporter</code> via an <code>NoteProvided</code> event.
* <code>Notifier</code> contains an <code>apply</code> method that takes a string and
* an optional payload object of type <code>Any</code>.
* The <code>Notifier</code> will forward the passed alert <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="NoteProvided.html"><code>NoteProvided</code></a> event.
* </p>
*
* <p>
* For insight into the differences between <code>Notifier</code>, <code>Alerter</code>, and <code>Informer</code>, see the
* main documentation for trait <a href="Notifying.html"><code>Notifying</code></a>.
* </p>
*/
trait Notifier {
/**
* Send a status update via an <code>NoteProvided</code> event to the reporter.
*/
def apply(message: String, payload: Option[Any] = None): Unit
}
|
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/AssertionsMacro.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.scalatest
import org.scalactic.BooleanMacro
import reflect.macros.Context
/**
* Macro implementation that provides rich error message for boolean expression assertion.
*/
private[scalatest] object AssertionsMacro {
/**
* Provides assertion implementation for <code>Assertions.assert(booleanExpr: Boolean)</code>, with rich error message.
*
* @param context macro context
* @param condition original condition expression
* @return transformed expression that performs the assertion check and throw <code>TestFailedException</code> with rich error message if assertion failed
*/
def assert(context: Context)(condition: context.Expr[Boolean]): context.Expr[Unit] =
new BooleanMacro[context.type](context, "assertionsHelper").genMacro(condition, "macroAssert", context.literal(""))
/**
* Provides assertion implementation for <code>Assertions.assert(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 assertion check and throw <code>TestFailedException</code> with rich error message (clue included) if assertion failed
*/
def assertWithClue(context: Context)(condition: context.Expr[Boolean], clue: context.Expr[Any]): context.Expr[Unit] =
new BooleanMacro[context.type](context, "assertionsHelper").genMacro(condition, "macroAssert", clue)
/**
* Provides implementation for <code>Assertions.assume(booleanExpr: Boolean)</code>, with rich error message.
*
* @param context macro context
* @param condition original condition expression
* @return transformed expression that performs the assumption check and throw <code>TestCanceledException</code> with rich error message if assumption failed
*/
def assume(context: Context)(condition: context.Expr[Boolean]): context.Expr[Unit] =
new BooleanMacro[context.type](context, "assertionsHelper").genMacro(condition, "macroAssume", context.literal(""))
/**
* Provides implementation for <code>Assertions.assume(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 assumption check and throw <code>TestCanceledException</code> with rich error message (clue included) if assumption failed
*/
def assumeWithClue(context: Context)(condition: context.Expr[Boolean], clue: context.Expr[Any]): context.Expr[Unit] =
new BooleanMacro[context.type](context, "assertionsHelper").genMacro(condition, "macroAssume", clue)
} |
cquiroz/scalatest | scalatest-test/src/test/scala/org/scalatest/TheSameElementsAsContainMatcherSpec.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 collection.mutable.LinkedHashMap
import SharedHelpers._
import Matchers._
import org.scalactic.Entry
class TheSameElementsAsContainMatcherSpec extends Spec {
object `theSameElementsAs ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: Any, lineNumber: Int) {
val leftText = FailureMessages.decorateToStringValue(left)
val rightText = FailureMessages.decorateToStringValue(right)
e.message should be (Some(leftText + " did not contain the same elements as " + rightText))
e.failedCodeFileName should be (Some("TheSameElementsAsContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeeded when left List contains same elements in same order as right List` {
List(1, 2, 3) should contain theSameElementsAs List(1, 2, 3)
Array(1, 2, 3) should contain theSameElementsAs List(1, 2, 3)
javaList(1, 2, 3) should contain theSameElementsAs List(1, 2, 3)
Map(1 -> "one", 2 -> "two", 3 -> "three") should contain theSameElementsAs Map(1 -> "one", 2 -> "two", 3 -> "three")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain theSameElementsAs List(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
}
def `should succeeded when left List contains same elements in different order as right List` {
List(1, 2, 3) should contain theSameElementsAs List(2, 1, 3)
Array(1, 2, 3) should contain theSameElementsAs List(2, 1, 3)
javaList(1, 2, 3) should contain theSameElementsAs List(2, 1, 3)
LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three") should contain theSameElementsAs LinkedHashMap(2 -> "two", 1 -> "one", 3 -> "three")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain theSameElementsAs List(Entry(2, "two"), Entry(1, "one"), Entry(3, "three"))
}
def `should succeeded when left List contains same elements in different order as right Set` {
List(1, 2, 3) should contain theSameElementsAs Set(2, 1, 3)
Array(1, 2, 3) should contain theSameElementsAs List(2, 1, 3)
javaList(1, 2, 3) should contain theSameElementsAs Set(2, 1, 3)
LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three") should contain theSameElementsAs LinkedHashMap(2 -> "two", 1 -> "one", 3 -> "three")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain theSameElementsAs List(Entry(2, "two"), Entry(1, "one"), Entry(3, "three"))
}
def `should succeeded when left List contains same elements in same order as right Set` {
List(1, 2, 3) should contain theSameElementsAs Set(1, 2, 3)
Array(1, 2, 3) should contain theSameElementsAs List(1, 2, 3)
javaList(1, 2, 3) should contain theSameElementsAs Set(1, 2, 3)
LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three") should contain theSameElementsAs LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain theSameElementsAs List(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
}
def `should succeeded when left Map contains same elements as right Map` {
Map(1 -> "one", 2 -> "two", 3 -> "three") should contain theSameElementsAs Map(1 -> "one", 2 -> "two", 3 -> "three")
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should contain theSameElementsAs List(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
}
def `should throw TestFailedException with correct stack depth and message when left and right List are same size but contain different elements` {
val left1 = List(1, 2, 3)
val right1 = List(2, 5, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(2 -> "two", 5 -> "five", 3 -> "three")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = List(2, 5, 3)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(2, "two"), Entry(5, "five"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(2, 5, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List is shorter than right List` {
val left1 = List(1, 2, 3)
val right1 = List(1, 2, 3, 4)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = List(1, 2, 3, 4)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"), Entry(4, "four"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(1, 2, 3, 4)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List is longer than right List` {
val left1 = List(1, 2, 3)
val right1 = List(1, 2)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(1 -> "one", 2 -> "two")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = List(1, 2)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(1, "one"), Entry(2, "two"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(1, 2)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List and right Set are same size but contain different elements` {
val left1 = List(1, 2, 3)
val right1 = Set(2, 5, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(2 -> "two", 5 -> "five", 3 -> "three")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = Set(2, 5, 3)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(2, "two"), Entry(5, "five"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(2, 5, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left and right List are not same size, though they contain same elements` {
val left1 = List(1, 2, 3, 3, 4)
val right1 = List(1, 2, 3, 4)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
// Also try in reverse, with left side a smaller collection
intercept[exceptions.TestFailedException] {
right1 should contain theSameElementsAs left1
}
val left2 = javaList(1, 2, 3, 3, 4)
val right2 = List(1, 2, 3, 4)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = Array(1, 2, 3, 3, 4)
val right3 = List(1, 2, 3, 4)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
// Also try in reverse, with left side a smaller collection
intercept[exceptions.TestFailedException] {
right3 should contain theSameElementsAs left3
}
}
def `should throw TestFailedException with correct stack depth and message when left List is shorter than right Set` {
val left1 = List(1, 2, 3)
val right1 = Set(1, 2, 3, 4)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(1 -> "one", 2 -> "two", 3 -> "three", 4 -> "four")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = Set(1, 2, 3, 4)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"), Entry(4, "four"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(1, 2, 3, 4)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List is longer than right Set` {
val left1 = List(1, 2, 3)
val right1 = Set(1, 2)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right2 = Map(1 -> "one", 2 -> "two")
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = javaList(1, 2, 3)
val right3 = Set(1, 2)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(1, "one"), Entry(2, "two"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should contain theSameElementsAs right4
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(1, 2)
val e5 = intercept[exceptions.TestFailedException] {
left5 should contain theSameElementsAs right5
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List does not contain all repeated elements in right List` {
val left1 = List(1, 1, 2)
val right1 = List(1, 2, 2)
val e1 = intercept[exceptions.TestFailedException] {
left1 should contain theSameElementsAs right1
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = javaList(1, 1, 2)
val right2 = List(1, 2, 2)
val e2 = intercept[exceptions.TestFailedException] {
left2 should contain theSameElementsAs right2
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = Array(1, 1, 2)
val right3 = List(1, 2, 2)
val e3 = intercept[exceptions.TestFailedException] {
left3 should contain theSameElementsAs right3
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
}
}
object `not theSameElementsAs ` {
def checkStackDepth(e: exceptions.StackDepthException, left: Any, right: Any, lineNumber: Int) {
val leftText = FailureMessages.decorateToStringValue(left)
val rightText = FailureMessages.decorateToStringValue(right)
e.message should be (Some(leftText + " contained the same elements as " + rightText))
e.failedCodeFileName should be (Some("TheSameElementsAsContainMatcherSpec.scala"))
e.failedCodeLineNumber should be (Some(lineNumber))
}
def `should succeeded when left List contains different elements as right List` {
List(1, 2, 3) should not contain theSameElementsAs (List(1, 2, 8))
Array(1, 2, 3) should not contain theSameElementsAs (List(1, 2, 8))
javaList(1, 2, 3) should not contain theSameElementsAs (List(1, 2, 8))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain theSameElementsAs (Map(1 -> "one", 2 -> "two", 8 -> "eight"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain theSameElementsAs (List(Entry(1, "one"), Entry(2, "two"), Entry(8, "eight")))
}
def `should succeeded when left List contains different elements in different order as right List` {
List(1, 2, 3) should not contain theSameElementsAs (List(2, 1, 8))
Array(1, 2, 3) should not contain theSameElementsAs (List(2, 1, 8))
javaList(1, 2, 3) should not contain theSameElementsAs (List(2, 1, 8))
Map(1 -> "one", 2 -> "two", 3 -> "three") should not contain theSameElementsAs (Map(2 -> "two", 1 -> "one", 8 -> "eight"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain theSameElementsAs (List(Entry(2, "two"), Entry(1, "one"), Entry(8, "eight")))
}
def `should succeeded when left List contains different elements in different order as right Set` {
List(1, 2, 3) should not contain theSameElementsAs (Set(2, 1, 8))
Array(1, 2, 3) should not contain theSameElementsAs (List(2, 1, 8))
javaList(1, 2, 3) should not contain theSameElementsAs (Set(2, 1, 8))
LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three") should not contain theSameElementsAs (LinkedHashMap(2 -> "two", 1 -> "one", 8 -> "eight"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain theSameElementsAs (List(Entry(2, "two"), Entry(1, "one"), Entry(8, "eight")))
}
def `should succeeded when left List contains different elements in same order as right Set` {
List(1, 2, 3) should not contain theSameElementsAs (Set(1, 2, 8))
Array(1, 2, 3) should not contain theSameElementsAs (List(1, 2, 8))
javaList(1, 2, 3) should not contain theSameElementsAs (Set(1, 2, 8))
LinkedHashMap(1 -> "one", 2 -> "two", 3 -> "three") should not contain theSameElementsAs (LinkedHashMap(1 -> "one", 2 -> "two", 8 -> "eight"))
javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three")) should not contain theSameElementsAs (List(Entry(1, "one"), Entry(2, "two"), Entry(8, "eight")))
}
def `should succeed when left and right List contains same element but has different size` {
List(1, 2, 3, 3, 4) should not contain theSameElementsAs (List(1, 2, 3, 4))
Array(1, 2, 3, 3, 4) should not contain theSameElementsAs (List(1, 2, 3, 4))
javaList(1, 2, 3, 3, 4) should not contain theSameElementsAs (List(1, 2, 3, 4))
}
def `should throw TestFailedException with correct stack depth and message when left and right List are same size but contain same elements in different order` {
val left1 = List(1, 2, 3)
val right1 = List(2, 1, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should not contain theSameElementsAs (right1)
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = javaList(1, 2, 3)
val right2 = List(2, 1, 3)
val e2 = intercept[exceptions.TestFailedException] {
left2 should not contain theSameElementsAs (right2)
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = Map(1 -> "one", 2 -> "two", 3 -> "three")
val right3 = Map(2 -> "two", 1 -> "one", 3 -> "three")
val e3 = intercept[exceptions.TestFailedException] {
left3 should not contain theSameElementsAs (right3)
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
val left4 = javaMap(Entry(1, "one"), Entry(2, "two"), Entry(3, "three"))
val right4 = List(Entry(2, "two"), Entry(1, "one"), Entry(3, "three"))
val e4 = intercept[exceptions.TestFailedException] {
left4 should not contain theSameElementsAs (right4)
}
checkStackDepth(e4, left4, right4, thisLineNumber - 2)
val left5 = Array(1, 2, 3)
val right5 = List(2, 1, 3)
val e5 = intercept[exceptions.TestFailedException] {
left5 should not contain theSameElementsAs (right5)
}
checkStackDepth(e5, left5, right5, thisLineNumber - 2)
}
def `should throw TestFailedException with correct stack depth and message when left List and right Set are same size but contain same elements in different order` {
val left1 = List(2, 3, 5)
val right1 = Set(2, 5, 3)
val e1 = intercept[exceptions.TestFailedException] {
left1 should not contain theSameElementsAs (right1)
}
checkStackDepth(e1, left1, right1, thisLineNumber - 2)
val left2 = Map(2 -> "two", 3 -> "three", 5 -> "five")
val right2 = Map(2 -> "two", 5 -> "five", 3 -> "three")
val e2 = intercept[exceptions.TestFailedException] {
left2 should not contain theSameElementsAs (right2)
}
checkStackDepth(e2, left2, right2, thisLineNumber - 2)
val left3 = Array(2, 3, 5)
val right3 = List(2, 5, 3)
val e3 = intercept[exceptions.TestFailedException] {
left3 should not contain theSameElementsAs (right3)
}
checkStackDepth(e3, left3, right3, thisLineNumber - 2)
}
}
}
|
cquiroz/scalatest | scalactic-macro/src/main/scala/org/scalactic/BooleanMacro.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
private[org] class BooleanMacro[C <: Context](val context: C, helperName: String) {
/*
* Translate the following:
*
* assert(something.aMethod == 3)
*
* to:
*
* {
* val $org_scalactic_assert_macro_left = something.aMethod
* val $org_scalactic_assert_macro_right = 3
* val $org_scalactic_assert_macro_result = $org_scalactic_assert_macro_left == $org_scalactic_assert_macro_result
* assertionsHelper.macroAssert($org_scalactic_assert_macro_left, "==", $org_scalactic_assert_macro_right, $org_scalactic_assert_macro_result, None)
* }
*
*/
/*
* Translate the following:
*
* assert(validate(1, 2, 3))
*
* to:
*
* assertionsHelper.macroAssert(validate(1, 2, 3), None)
*
*/
import context.universe._
// Generate AST for:
// val name = rhs
def valDef(name: String, rhs: Tree): ValDef =
ValDef(
Modifiers(),
newTermName(name),
TypeTree(),
rhs
)
private val logicOperators = Set("&&", "||", "&", "|")
private val supportedBinaryOperations =
Set(
"==",
"!=",
"===",
"!==",
"<",
">",
">=",
"<=",
"startsWith",
"endsWith",
"contains",
"eq",
"ne",
"exists") ++ logicOperators
private val supportedUnaryOperations =
Set(
"unary_!",
"isEmpty"
)
private val lengthSizeOperations =
Set(
"length",
"size"
)
def isSupportedBinaryOperator(operator: String) = supportedBinaryOperations.contains(operator)
def isSupportedUnaryOperator(operator: String) = supportedUnaryOperations.contains(operator)
def isSupportedLengthSizeOperator(operator: String) = lengthSizeOperations.contains(operator)
private[this] def getPosition(expr: Tree) = expr.pos.asInstanceOf[scala.reflect.internal.util.Position]
/**
* Get text of the expression, current it'll try to look for RangePosition (only available when -Yrange.pos is enabled),
* else it will just call show to get the text.
*/
def getText(expr: Tree): String = {
expr match {
case literal: Literal =>
getPosition(expr) match {
case p: scala.reflect.internal.util.RangePosition => p.lineContent.slice(p.start, p.end).trim // this only available when -Yrangepos is enabled
case p: reflect.internal.util.Position => ""
}
case _ => show(expr)
}
}
/**
* For binary method call, for example left.aMethodCall(right), it'll generate the AST for the following code:
*
* org.scalactic.Bool.binaryMacroBool($org_scalatest_assert_macro_left, "aMethodCall", $org_scalatest_assert_macro_right, $org_scalatest_assert_macro_left.aMethodCall($org_scalatest_assert_macro_right))
*/
def binaryMacroBool(select: Select): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("binaryMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
Ident(newTermName("$org_scalatest_assert_macro_right")),
Apply(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
select.name
),
List(Ident(newTermName("$org_scalatest_assert_macro_right")))
)
)
)
/**
* For === and !== method call that takes Equality, for example left === right, it'll generate the AST for the following code:
*
* org.scalactic.Bool.binaryMacroBool($org_scalatest_assert_macro_left, "===", $org_scalatest_assert_macro_right, $org_scalatest_assert_macro_left.===($org_scalatest_assert_macro_right)(defaultEquality))
*/
def binaryMacroBool(select: Select, secondArg: Tree): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("binaryMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
Ident(newTermName("$org_scalatest_assert_macro_right")),
Apply(
Apply(
Select(
Ident("$org_scalatest_assert_macro_left"),
select.name
),
List(Ident("$org_scalatest_assert_macro_right"))
),
List(secondArg)
)
)
)
/**
* For === and !== method call that takes Equality and uses TypeCheckedTripleEquals , for example left === right, it'll generate the AST for the following code:
*
* org.scalactic.Bool.binaryMacroBool($org_scalatest_assert_macro_left, "===", $org_scalatest_assert_macro_right, $org_scalatest_assert_macro_left.===[R]($org_scalatest_assert_macro_right)(defaultEquality))
*/
def typedBinaryMacroBool(select: Select, typeArgs: List[Tree]): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("binaryMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
Ident(newTermName("$org_scalatest_assert_macro_right")),
Apply(
TypeApply(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
select.name
),
typeArgs
),
List(Ident(newTermName("$org_scalatest_assert_macro_right")))
)
)
)
/**
* For unrecognized expression, it'll generate the AST for the following code:
*
* org.scalactic.Bool.simpleMacroBool(expression, expressionText) // expressionText is currently the text returned from 'show'
*/
def simpleMacroBool(expression: Tree, expressionText: String): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("simpleMacroBool")
),
List(
expression,
context.literal(expressionText).tree
)
)
/**
* For !a unary_! call, it'll generate the AST for the following code:
*
* org.scalactic.Bool.notBool(a)
*/
def notBool(target: Tree): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("notBool")
),
List(
target.duplicate
)
)
/**
* For a.isEmpty and method call that does not has any argument, it'll generate the AST for the following code:
*
* org.scalactic.Bool.unaryMacroBool($org_scalatest_assert_macro_left, "isEmpty", $org_scalatest_assert_macro_left.isEmpty)
*/
def unaryMacroBool(select: Select): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("unaryMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
select.name
)
)
)
/**
* For a.isInstanceOf[String] == 1, it'll generate the AST for the following code:
*
* org.scalactic.Bool.lengthSizeMacroBool($org_scalatest_assert_macro_left, "==", $org_scalatest_assert_macro_left.length, 1)
*/
def isInstanceOfMacroBool(select: Select, className: String, typeArg: Tree): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("isInstanceOfMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
context.literal(className).tree,
TypeApply(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
select.name
),
List(typeArg)
)
)
)
/**
* For a.length == 1, it'll generate the AST for the following code:
*
* org.scalactic.Bool.lengthSizeMacroBool($org_scalatest_assert_macro_left, "==", $org_scalatest_assert_macro_left.length, 1)
*/
def lengthSizeMacroBool(select: Select): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("lengthSizeMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
context.literal(select.name.decoded).tree,
Select(
Ident("$org_scalatest_assert_macro_left"),
select.name
),
Ident(newTermName("$org_scalatest_assert_macro_right"))
)
)
/**
* generate the AST for the following code:
*
* org.scalactic.Bool.existsMacroBool($org_scalatest_assert_macro_left, $org_scalatest_assert_macro_right, $org_scalatest_assert_macro_left.exists(func))
*/
def existsMacroBool(select: Select, func: Function): Apply =
Apply(
Select(
Select(
Select(
Select(
Ident(newTermName("_root_")),
newTermName("org")
),
newTermName("scalactic")
),
newTermName("Bool")
),
newTermName("existsMacroBool")
),
List(
Ident(newTermName("$org_scalatest_assert_macro_left")),
Ident(newTermName("$org_scalatest_assert_macro_right")),
Apply(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
select.name
),
List(
func
)
)
)
)
// traverse the given Select, both qualifier and the right expression.
def traverseSelect(select: Select, rightExpr: Tree): (Tree, Tree) = {
val operator = select.name.decoded
if (logicOperators.contains(operator)) {
val leftTree = // traverse the qualifier
select.qualifier match {
case selectApply: Apply => transformAst(selectApply.duplicate)
case selectSelect: Select => transformAst(selectSelect.duplicate)
case _ => simpleMacroBool(select.qualifier.duplicate, getText(select.qualifier))
}
val rightTree = {
val evalBlock =
rightExpr match {
case argApply: Apply => transformAst(argApply.duplicate)
case argSelect: Select => transformAst(argSelect)
case argTypeApply: TypeApply => transformAst(argTypeApply.duplicate)
case _ => simpleMacroBool(rightExpr.duplicate, getText(rightExpr))
}
if (operator == "&&" || operator == "&") {// generate if (left.value) {...} else false
If(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
newTermName("value")
),
evalBlock,
simpleMacroBool(context.literal(false).tree, "")
)
}
else if (operator == "||" || operator == "|") // || and |, generate if (left.value) true else {...}
If(
Select(
Ident(newTermName("$org_scalatest_assert_macro_left")),
newTermName("value")
),
simpleMacroBool(context.literal(true).tree, ""),
evalBlock
)
else
evalBlock
}
(leftTree, rightTree)
}
else
(select.qualifier.duplicate, rightExpr.duplicate)
}
// helper method to check if the given tree represent a place holder syntax
private def isPlaceHolder(tree: Tree): Boolean =
tree match {
case valDef: ValDef => valDef.rhs == EmptyTree
case _ => false
}
/**
* Transform the passed in boolean expression, see comment in different case for details
*/
def transformAst(tree: Tree): Tree = {
tree match {
case apply: Apply if apply.args.size == 1 =>
apply.fun match {
case select: Select if isSupportedBinaryOperator(select.name.decoded) =>
val operator = select.name.decoded
val (leftTree, rightTree) = traverseSelect(select, apply.args(0))
operator match {
case "==" =>
leftTree match {
case leftApply: Apply =>
leftApply.fun match {
case leftApplySelect: Select if isSupportedLengthSizeOperator(leftApplySelect.name.decoded) && leftApply.args.size == 0 =>
/**
* support for a.length() == xxx, a.size() == xxxx
*
* generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = {qualifier of the method call}
* val $org_scalatest_assert_macro_right = {first argument}
* [code generated from lengthSizeMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftApplySelect.qualifier.duplicate),
valDef("$org_scalatest_assert_macro_right", rightTree),
lengthSizeMacroBool(leftApplySelect.duplicate)
)
case _ =>
/**
* something else but still a binary macro bool, generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = {qualifier of the method call}
* val $org_scalatest_assert_macro_right = {first argument}
* [code generated from binaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
binaryMacroBool(select.duplicate)
)
}
case leftSelect: Select if isSupportedLengthSizeOperator(leftSelect.name.decoded) =>
/**
* support for a.length == xxx, a.size == xxxx
*
* generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = {qualifier of the method call}
* val $org_scalatest_assert_macro_right = {first argument}
* [code generated from binaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftSelect.qualifier.duplicate),
valDef("$org_scalatest_assert_macro_right", rightTree),
lengthSizeMacroBool(leftSelect.duplicate)
)
case _ =>
/**
* something else but still a binary macro bool, generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = {qualifier of the method call}
* val $org_scalatest_assert_macro_right = {first argument}
* [code generated from binaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
binaryMacroBool(select.duplicate)
)
}
case "exists" =>
rightTree match {
case func: Function if func.children.size == 2 && isPlaceHolder(func.children(0)) =>
val boolExpr = func.children(1)
boolExpr match {
case boolExprApply: Apply if boolExprApply.args.size == 1 =>
boolExprApply.fun match {
case boolExprApplySelect: Select if boolExprApplySelect.name.decoded == "==" =>
/**
* support for a.exists(_ == 2), generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* val $org_scalatest_assert_macro_right = _ == 2 // after desugar
* [code generated from existsMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", boolExprApply.args(0).duplicate),
existsMacroBool(select.duplicate, func.duplicate)
)
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case _ =>
/**
* something else but still a binary macro bool, generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = {qualifier of the method call}
* val $org_scalatest_assert_macro_right = {first argument}
* [code generated from binaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
binaryMacroBool(select.duplicate)
)
}
case funApply: Apply if funApply.args.size == 1 =>
funApply.fun match {
case select: Select if select.name.decoded == "===" || select.name.decoded == "!==" =>
val (leftTree, rightTree) = traverseSelect(select, funApply.args(0))
/**
* For === and !== that takes Equality, for example a === b
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* val $org_scalatest_assert_macro_right = b
* [code generated from binaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
binaryMacroBool(select.duplicate, apply.args(0).duplicate) // TODO: should apply.args(0) be traversed also?
)
case typeApply: TypeApply =>
typeApply.fun match {
case select: Select if typeApply.args.size == 1 =>
/**
* For === and !== that takes Equality and uses TypeCheckedTripleEquals, for example a === b
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* val $org_scalatest_assert_macro_right = b
* [code generated from binaryMacroBool]
* }
*/
val operator: String = select.name.decoded
if (operator == "===" || operator == "!==") {
val (leftTree, rightTree) = traverseSelect(select, funApply.args(0))
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
binaryMacroBool(select.duplicate, apply.args(0).duplicate) // TODO: should apply.args(0) be traversed also?
)
}
else
simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case funTypeApply: TypeApply =>
/**
* For binary bool expression that takes typed parameter, for example the contains method in scala 2.11, a.contains(b)
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* val $org_scalatest_assert_macro_right = b
* [code generated from typedBinaryMacroBool]
* }
*/
funTypeApply.fun match {
case select: Select if isSupportedBinaryOperator(select.name.decoded) =>
val (leftTree, rightTree) = traverseSelect(select, apply.args(0))
Block(
valDef("$org_scalatest_assert_macro_left", leftTree),
valDef("$org_scalatest_assert_macro_right", rightTree),
typedBinaryMacroBool(select.duplicate, funTypeApply.args)
)
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case apply: Apply if apply.args.size == 0 =>
/**
* For unary operation that takes 0 arguments, for example a.isEmpty
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* [code generated from unaryMacroBool]
* }
*/
apply.fun match {
case select: Select if isSupportedUnaryOperator(select.name.decoded) =>
Block(
valDef("$org_scalatest_assert_macro_left", select.qualifier.duplicate),
unaryMacroBool(select.duplicate)
)
case _ => simpleMacroBool(tree.duplicate, getText(tree))
}
case typeApply: TypeApply if typeApply.args.length == 1 =>
typeApply.fun match {
case select: Select =>
val operator = select.name.decoded
if (operator == "isInstanceOf") {
/**
* For isInstanceOf support, for example a.isInstanceOf[String]
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* [code generated from isInstanceOfMacroBool]
* }
*/
typeApply.args(0).tpe match {
case typeRef: TypeRef =>
Block(
valDef("$org_scalatest_assert_macro_left", select.qualifier.duplicate),
isInstanceOfMacroBool(select.duplicate, typeRef.sym.fullName, typeApply.args(0).duplicate)
)
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
}
else
simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
case _ => simpleMacroBool(tree.duplicate, getText(tree)) // something else, just call simpleMacroBool
}
case select: Select if supportedUnaryOperations.contains(select.name.decoded) => // for ! and unary operation that does not take any arguments
if (select.name.decoded == "unary_!") {
/**
* For unary_! operation, for example !a
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* [code generated from notBool]
* }
*/
val leftTree =
select.qualifier match {
case selectApply: Apply => transformAst(selectApply.duplicate)
case selectSelect: Select => transformAst(selectSelect.duplicate)
case selectTypeApply: TypeApply => transformAst(selectTypeApply.duplicate)
case _ => simpleMacroBool(select.qualifier.duplicate, getText(select.qualifier))
}
notBool(leftTree.duplicate)
}
else {
/**
* For unary operation that does not take any arguments, for example a.isEmpty
*
* will generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_left = a
* [code generated from unaryMacroBool]
* }
*/
Block(
valDef("$org_scalatest_assert_macro_left", select.qualifier.duplicate),
unaryMacroBool(select.duplicate)
)
}
case _ =>
simpleMacroBool(tree.duplicate, getText(tree))// something else, just call simpleMacroBool
}
}
/**
* Generate AST for the following code:
*
* {helperName}.{methodName}($org_scalatest_assert_macro_expr, clue)
*/
def callHelper(methodName: String, clueTree: Tree): Apply =
Apply(
Select(
Ident(newTermName(helperName)),
newTermName(methodName)
),
List(Ident(newTermName("$org_scalatest_assert_macro_expr")), clueTree)
)
/**
* Generate AST for the following code:
*
* {
* val $org_scalatest_assert_macro_expr = [code generated from transformAst]
* [code generated from callHelper]
* }
*/
def genMacro(booleanExpr: Expr[Boolean], methodName: String, clueExpr: Expr[Any]): Expr[Unit] = {
val ownerRepair = new MacroOwnerRepair[context.type](context)
val expandedCode =
context.Expr(
Block(
valDef("$org_scalatest_assert_macro_expr", transformAst(booleanExpr.tree)),
callHelper(methodName, clueExpr.tree)
)
)
ownerRepair.repairOwners(expandedCode)
}
} |
cquiroz/scalatest | scalatest/src/main/scala/org/scalatest/DocSpecLike.scala | <filename>scalatest/src/main/scala/org/scalatest/DocSpecLike.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.xml.Elem
import Suite.reportMarkupProvided
import DocSpec.stripMargin
import DocSpec.trimMarkup
import java.util.concurrent.atomic.AtomicReference
import java.util.ConcurrentModificationException
import collection.mutable.ListBuffer
import Suite.reportMarkupProvided
import scala.collection.mutable.ListBuffer
private[scalatest] trait DocSpecLike extends Suite with Informing with Notifying with Alerting { thisSuite =>
private final val engine = new Engine(Resources.concurrentFunSuiteMod, "FunSuite")
import engine._
/**
* Returns an <code>Informer</code> that during test execution will forward strings (and other objects) passed to its
* <code>apply</code> method to the current reporter. If invoked in a constructor, it
* will register the passed string for forwarding later during test execution. If invoked while this
* <code>FeatureSpec</code> is being executed, such as from inside a test function, it will forward the information to
* the current reporter immediately. If invoked at any other time, it will
* throw an exception. This method can be called safely by any thread.
*/
protected def info: Informer = atomicInformer.get
protected def note: Notifier = atomicNotifier.get
protected def alert: Alerter = atomicAlerter.get
sealed abstract class Snippet
case class MarkupSnippet(text: String) extends Snippet
case class SuiteSnippet(suite: Suite) extends Snippet
implicit class MarkupContext(val sc: StringContext) {
def markup(suites: Suite*): IndexedSeq[Snippet] = {
val stringIt = sc.parts.iterator
val suiteIt = suites.iterator
// There will always be at least one element in stringIt, though
// it could be empty.
val buf = new ListBuffer[Snippet]
val initialString = stringIt.next // don't trim, because \n's are important in markup
if (!initialString.isEmpty) // But I'm guessing if a suite is the very first thing, we'll get an empty initial string
buf += MarkupSnippet(initialString)
// If there's another string, that means there's another
// suite before it. The last string may again be empty.
while (stringIt.hasNext) {
buf += SuiteSnippet(suiteIt.next)
buf += MarkupSnippet(stringIt.next)
}
// buf.toVector
Vector.empty ++ buf // While supporting 2.9
}
}
protected override def runNestedSuites(args: Args): Status = {
import args._
for (snippet <- doc) {
snippet match {
case SuiteSnippet(suite) =>
// Need to of course compose these, but also need the darned
// status to make a checkmark. And want the stuff to come out
// in a nice order in the text output. Hmm. I think this is the
// sorting thing? Yes, this one started first, so it gets sorted
// and preferred until it is done. The checkmark could go out as
// a markup, but trouble is that I kind of want a real checkmark.
// Like mocha did in the output, and in the HTML.
suite.run(None, args)
case MarkupSnippet(text) =>
reportMarkupProvided(thisSuite, reporter, tracker, None, trimMarkup(stripMargin(text)), 0, None, true)
}
}
SucceededStatus
}
val doc: IndexedSeq[Snippet]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.