org.scalatest.Suite.scala Maven / Gradle / Ivy
/* * 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.{Resources => _, NameUtil, Requirements} import org.scalatest.events.{ TopOfClass, Formatter, Location, TopOfMethod, IndentedText, RunStarting, SuiteAborted, SuiteStarting, SeeStackDepthException, SuiteCompleted, RunCompleted, RunAborted, InfoProvided, NameInfo, MotionToSuppress, RecordableEvent, TestFailed, TestStarting, TestPending, TestCanceled, TestSucceeded, NoteProvided, AlertProvided, MarkupProvided, ScopeOpened, ScopeClosed, ScopePending, LineInFile, TestIgnored } import Requirements.requireNonNull import org.scalatest.exceptions._ import java.lang.annotation.AnnotationFormatError import java.lang.reflect.{Method, Modifier} import java.nio.charset.CoderMalfunctionError import javax.xml.parsers.FactoryConfigurationError import javax.xml.transform.TransformerFactoryConfigurationError import org.scalactic.Prettifier import org.scalatest.time.{Seconds, Span} import scala.collection.immutable.TreeSet import scala.util.control.NonFatal import org.scalatest.exceptions.StackDepthExceptionHelper._ import Suite.formatterForSuiteAborted import Suite.formatterForSuiteCompleted import Suite.formatterForSuiteStarting import Suite.getEscapedIndentedTextForTest import NameUtil.getSimpleNameOfAnObjectsClass import Suite.getTopOfMethod import Suite.isTestMethodGoodies import Suite.reportTestIgnored import Suite.takesInformer import Suite.getSuiteClassName import org.scalatest.tools.Utils.wrapReporterIfNecessary import annotation.tailrec import collection.GenTraversable import collection.mutable.ListBuffer // SKIP-SCALATESTJS,NATIVE-START import Suite.getTopOfClass import org.scalatest.tools.StandardOutReporter import tools.SuiteDiscoveryHelper // SKIP-SCALATESTJS,NATIVE-END /* *
* will be run. However, ifUsing
* *info
andmarkup
* One of the parameters to
* *Suite
'srun
method is aReporter
, which * will collect and report information about the running suite of tests. * Information about suites and tests that were run, whether tests succeeded or failed, * and tests that were ignored will be passed to theReporter
as the suite runs. * Most often the reporting done by default will be sufficient, but * occasionally you may wish to provide custom information to theReporter
from a test. * For this purpose, anInformer
that will forward information * to the currentReporter
is provided via theinfo
parameterless method. * You can pass the extra information to theInformer
via itsapply
method. * TheInformer
will then pass the information to theReporter
via anInfoProvided
event. * Here's an example that shows both a direct use as well as an indirect use through the methods * ofGivenWhenThen
: ** package org.scalatest.examples.suite.info * * import collection.mutable * import org.scalatest._ * * class SetSuite extends Suite with GivenWhenThen { * * def `test: an element can be added to an empty mutable Set` { * * given("an empty mutable Set") * val set = mutable.Set.empty[String] * * when("an element is added") * set += "clarity" * * then("the Set should have size 1") * assert(set.size === 1) * * and("the Set should contain the added element") * assert(set.contains("clarity")) * * info("That's all folks!") * } * } ** * If you run thisSuite
from the interpreter, you will see the messages * included in the output: * ** scala> org.scalatest.run(new SetSuite) * SetSuite: * - an element can be added to an empty mutable Set * + Given an empty mutable Set * + When an element is added * + Then the Set should have size 1 * + And the Set should contain the added element * + That's all folks! *
* ** Trait
* -------------- *Suite
also carries aDocumenter
namedmarkup
, which * you can use to transmit markup text to theReporter
. *Assertions and
* *=
=
=
* Inside test methods in a
* *Suite
, you can write assertions by invokingassert
and passing in aBoolean
expression, * such as: ** val left = 2 * val right = 1 * assert(left == right) ** ** If the passed expression is
* *true
,assert
will return normally. Iffalse
, *assert
will complete abruptly with aTestFailedException
. This exception is usually not caught * by the test method, which means the test method itself will complete abruptly by throwing theTestFailedException
. Any * test method that completes abruptly with an exception is considered a failed * test. A test method that returns normally is considered a successful test. ** If you pass a
* *Boolean
expression toassert
, a failed assertion will be reported, but without * reporting the left and right values. You can alternatively encode these values in aString
passed as * a second argument toassert
, as in: ** val left = 2 * val right = 1 * assert(left == right, left + " did not equal " + right) ** ** Using this form of
* *assert
, the failure report will include the left and right values, * helping you debug the problem. However, ScalaTest provides the===
operator to make this easier. * (The===
operator is defined in traitAssertions
which traitSuite
extends.) * You use it like this: ** val left = 2 * val right = 1 * assert(left === right) ** ** Because you use
* *===
here instead of==
, the failure report will include the left * and right values. For example, the detail message in the thrownTestFailedException
from theassert
* shown previously will include, "2 did not equal 1". * From this message you will know that the operand on the left had the value 2, and the operand on the right had the value 1. ** If you're familiar with JUnit, you would use
* *===
* in a ScalaTestSuite
where you'd useassertEquals
in a JUnitTestCase
. * The===
operator is made possible by an implicit conversion fromAny
* toEqualizer
. If you're curious to understand the mechanics, see the documentation for *Equalizer
and theconvertToEqualizer
method. *Expected results
* * Although===
provides a natural, readable extension to Scala'sassert
mechanism, * as the operands become lengthy, the code becomes less readable. In addition, the===
comparison * doesn't distinguish between actual and expected values. The operands are just calledleft
andright
, * because if one were namedexpected
and the otheractual
, it would be difficult for people to * remember which was which. To help with these limitations of assertions,Suite
includes a method calledassertResult
that * can be used as an alternative toassert
with===
. To useassertResult
, you place * the expected value in parentheses afterassertResult
, followed by curly braces containing code * that should result in the expected value. For example: * ** val a = 5 * val b = 2 * assertResult(2) { * a - b * } ** ** In this case, the expected value is
* *2
, and the code being tested isa - b
. This expectation will fail, and * the detail message in theTestFailedException
will read, "Expected 2, but got 3." *Intercepted exceptions
* ** Sometimes you need to test whether a method throws an expected exception under certain circumstances, such * as when invalid arguments are passed to the method. You can do this in the JUnit style, like this: *
* ** val s = "hi" * try { * s.charAt(-1) * fail() * } * catch { * case _: IndexOutOfBoundsException => // Expected, so continue * } ** ** If
* *charAt
throwsIndexOutOfBoundsException
as expected, control will transfer * to the catch case, which does nothing. If, however,charAt
fails to throw an exception, * the next statement,fail()
, will be executed. Thefail
method always completes abruptly with * aTestFailedException
, thereby signaling a failed test. ** To make this common use case easier to express and read, ScalaTest provides an
* *intercept
* method. You use it like this: ** val s = "hi" * intercept[IndexOutOfBoundsException] { * s.charAt(-1) * } ** ** This code behaves much like the previous example. If
* *charAt
throws an instance ofIndexOutOfBoundsException
, *intercept
will return that exception. But ifcharAt
completes normally, or throws a different * exception,intercept
will complete abruptly with aTestFailedException
. Theintercept
method returns the * caught exception so that you can inspect it further if you wish, for example, to ensure that data contained inside * the exception has the expected values. Here's an example: ** val s = "hi" * val caught = * intercept[IndexOutOfBoundsException] { * s.charAt(-1) * } * assert(caught.getMessage === "String index out of range: -1") ** *Using matchers and other assertions
* ** ScalaTest also supports another style of assertions via its matchers DSL. By mixing in * trait
* *Matchers
, you can * write suites that look like: ** package org.scalatest.examples.suite.matchers * * import org.scalatest._ * * class SetSuite extends Suite with Matchers { * * def `test: an empty Set should have size 0` { * Set.empty.size should equal (0) * } * * def `test: invoking head on an empty Set should produce NoSuchElementException` { * a [NoSuchElementException] should be thrownBy { Set.empty.head } * } * } ** *If you prefer the word "
* *must
" to the word "should
," you can alternatively mix in * traitMustMatchers
. ** If you are comfortable with assertion mechanisms from other test frameworks, chances * are you can use them with ScalaTest. Any assertion mechanism that indicates a failure with an exception * can be used as is with ScalaTest. For example, to use the
*/ /** * A suite of tests. AassertEquals
* methods provided by JUnit or TestNG, simply import them and use them. (You will of course need * to include the relevant JAR file for the framework whose assertions you want to use on either the * classpath or runpath when you run your tests.) *Suite
instance encapsulates a conceptual * suite (i.e., a collection) of tests. * ** This trait provides an interface composed of "lifecycle methods" that allow suites of tests to be run. * Its implementation enables a default way of writing and executing tests. Subtraits and subclasses can * override
* *Suite
's lifecycle methods to enable other ways of writing and executing tests. *Nested suites
* ** A
* *Suite
can refer to a collection of otherSuite
s, * which are called nestedSuite
s. Those nestedSuite
s can in turn have * their own nestedSuite
s, and so on. Large test suites can be organized, therefore, as a tree of * nestedSuite
s. * This trait'srun
method, in addition to invoking its * test methods, invokesrun
on each of its nestedSuite
s. ** A
* *List
of aSuite
's nestedSuite
s can be obtained by invoking its *nestedSuites
method. If you wish to create aSuite
that serves as a * container for nestedSuite
s, whether or not it has test methods of its own, simply overridenestedSuites
* to return aList
of the nestedSuite
s. Because this is a common use case, ScalaTest provides * a convenienceSuites
class, which takes a variable number of nestedSuite
s as constructor * parameters. Here's an example: ** package org.scalatest.examples.suite.nested * * import org.scalatest._ * * class ASuite extends FunSuite { * test("A should have ASCII value 41 hex") { * assert('A' === 0x41) * } * test("a should have ASCII value 61 hex") { * assert('a' === 0x61) * } * } * class BSuite extends FunSuite { * test("B should have ASCII value 42 hex") { * assert('B' === 0x42) * } * test("b should have ASCII value 62 hex") { * assert('b' === 0x62) * } * } * class CSuite extends FunSuite { * test("C should have ASCII value 43 hex") { * assert('C' === 0x43) * } * test("c should have ASCII value 63 hex") { * assert('c' === 0x63) * } * } * * class ASCIISuite extends Suites( * new ASuite, * new BSuite, * new CSuite * ) ** ** If you now run
* *ASCIISuite
: ** scala> org.scalatest.run(new ASCIISuite) ** ** You will see reports printed to the standard output that indicate the nested * suites—
* *ASuite
,BSuite
, and *CSuite
—were run: ** ASCIISuite: * ASuite: * - A should have ASCII value 41 hex * - a should have ASCII value 61 hex * BSuite: * - B should have ASCII value 42 hex * - b should have ASCII value 62 hex * CSuite: * - C should have ASCII value 43 hex * - c should have ASCII value 63 hex *
* ** Note that
* *Runner
can discoverSuite
s automatically, so you need not * necessarily define nestedSuites
explicitly. See the documentation * forRunner
for more information. *The config map
* ** In some cases you may need to pass information to a suite of tests. * For example, perhaps a suite of tests needs to grab information from a file, and you want * to be able to specify a different filename during different runs. You can accomplish this in ScalaTest by passing * the filename in a config map of key-value pairs, which is passed to
* *run
as aConfigMap
. * The values in the config map are called "config objects," because they can be used to configure * suites, reporters, and tests. ** You can specify a string config object is via the ScalaTest
* *Runner
, either via the command line * or ScalaTest's ant task. * (See the documentation for Runner for information on how to specify * config objects on the command line.) * The config map is passed torun
,runNestedSuites
,runTests
, andrunTest
, * so one way to access it in your suite is to override one of those methods. If you need to use the config map inside your tests, you * can access it from theNoArgTest
passed towithFixture
, or theOneArgTest
passed to *withFixture
in the traits in theorg.scalatest.fixture
package. (See the * documentation forFixtureSuite
* for instructions on how to access the config map in tests.) *Executing suites in parallel
* ** The
* * *run
method takes as one of its parameters an optionalDistributor
. If * aDistributor
is passed in, this trait's implementation ofrun
puts its nested *Suite
s into the distributor rather than executing them directly. The caller ofrun
* is responsible for ensuring that some entity runs theSuite
s placed into the * distributor. The-P
command line parameter toRunner
, for example, will cause *Suite
s put into theDistributor
to be run in parallel via a pool of threads. * If you wish to execute the tests themselves in parallel, mix inParallelTestExecution
. *"Run-aborting" exceptions
* ** The Javadoc documentation for
* *java.lang.Error
states: ** An* *Error
is a subclass ofThrowable
that indicates serious problems that a reasonable application * should not try to catch. Most * such errors are abnormal conditions. ** Because
* *Error
s are used to denote serious errors, traitSuite
and its subtypes in the ScalaTest API * do not always treat a test that completes abruptly with anError
as a test failure, but sometimes as an indication * that serious problems have arisen that should cause the run to abort. For example, if a test completes abruptly with an *OutOfMemoryError
, it will not be reported as a test failure, but will instead cause the run to abort. Because not * everyone usesError
s only to represent serious * problems, however, ScalaTest only behaves this way for the following run-aborting exception types (and their subclasses): **
* *- *
java.lang.annotation.AnnotationFormatError
- *
java.awt.AWTError
- *
java.nio.charset.CoderMalfunctionError
- *
javax.xml.parsers.FactoryConfigurationError
- *
java.lang.LinkageError
- *
java.lang.ThreadDeath
- *
javax.xml.transform.TransformerFactoryConfigurationError
- *
java.lang.VirtualMachineError
* The previous list includes all
* *Error
s that exist as part of Java 1.5 API, excludingjava.lang.AssertionError
. * ScalaTest does treat a thrownAssertionError
as an indication of a test failure. In addition, any other *Error
that is not an instance of a type mentioned in the previous list will be caught by theSuite
traits * in the ScalaTest API and reported as the cause of a test failure. ** Although trait
* * *Suite
and all its subtypes in the ScalaTest API consistently behave this way with regard toError
s, * this behavior is not required by the contract ofSuite
. Subclasses and subtraits that you define, for example, may treat all *Error
s as test failures, or indicate errors in some other way that has nothing to do with exceptions. *Extensibility
* ** Trait
* *Suite
provides default implementations of its methods that should * be sufficient for most applications, but many methods can be overridden when desired. Here's * a summary of the methods that are intended to be overridden: **
* *- *
run
- override this method to define custom ways to run suites of * tests.- *
runNestedSuites
- override this method to define custom ways to run nested suites.- *
runTests
- override this method to define custom ways to run a suite's tests.- *
runTest
- override this method to define custom ways to run a single named test.- *
testNames
- override this method to specify theSuite
's test names in a custom way.- *
tags
- override this method to specify theSuite
's test tags in a custom way.- *
nestedSuites
- override this method to specify theSuite
's nestedSuite
s in a custom way.- *
suiteName
- override this method to specify theSuite
's name in a custom way.- *
expectedTestCount
- override this method to count thisSuite
's expected tests in a custom way.* For example, this trait's implementation of
* *testNames
performs reflection to discover methods starting withtest
, * and places these in aSet
whose iterator returns the names in alphabetical order. If you wish to run tests in a different * order in a particularSuite
, perhaps because a test namedtestAlpha
can only succeed after a test named *testBeta
has run, you can overridetestNames
so that it returns aSet
whose iterator returns *testBeta
beforetestAlpha
. (This trait's implementation ofrun
will invoke tests * in the order they come out of thetestNames
Set
iterator.) ** Alternatively, you may not like starting your test methods with
* *test
, and prefer using@Test
annotations in * the style of Java's JUnit 4 or TestNG. If so, you can overridetestNames
to discover tests using either of these two APIs *@Test
annotations, or one of your own invention. (This is in fact * howorg.scalatest.junit.JUnitSuite
andorg.scalatest.testng.TestNGSuite
work.) ** Moreover, test in ScalaTest does not necessarily mean test method. A test can be anything that can be given a name, * that starts and either succeeds or fails, and can be ignored. In
* *org.scalatest.FunSuite
, for example, tests are represented * as function values. This * approach might look foreign to JUnit users, but may feel more natural to programmers with a functional programming background. * To facilitate this style of writing tests,FunSuite
overridestestNames
,runTest
, andrun
such that you can * define tests as function values. ** You can also model existing JUnit 3, JUnit 4, or TestNG tests as suites of tests, thereby incorporating tests written in Java into a ScalaTest suite. * The "wrapper" classes in packages
* * @author Bill Venners */ trait Suite extends Assertions with Serializable { thisSuite => import Suite.InformerInParens /** * An immutableorg.scalatest.junit
andorg.scalatest.testng
exist to make this easy. * No matter what legacy tests you may have, it is likely you can create or use an existingSuite
subclass that allows you to model those tests * as ScalaTest suites and tests and incorporate them into a ScalaTest suite. You can then write new tests in Scala and continue supporting * older tests in Java. *IndexedSeq
of thisSuite
object's nestedSuite
s. If thisSuite
contains no nestedSuite
s, * this method returns an emptyIndexedSeq
. This trait's implementation of this method returns an emptyList
. */ def nestedSuites: collection.immutable.IndexedSeq[Suite] = Vector.empty // SKIP-SCALATESTJS,NATIVE-START /** * Executes one or more tests in thisSuite
, printing results to the standard output. * ** This method invokes
* *run
on itself, passing in values that can be configured via the parameters to this * method, all of which have default values. This behavior is convenient when working with ScalaTest in the Scala interpreter. * Here's a summary of this method's parameters and how you can use them: ** The
* *testName
parameter ** If you leave
* *testName
at its default value (ofnull
), this method will passNone
to * thetestName
parameter ofrun
, and as a result all the tests in this suite will be executed. If you * specify atestName
, this method will passSome(testName)
torun
, and only that test * will be run. Thus to run all tests in a suite from the Scala interpreter, you can write: ** scala> (new ExampleSuite).execute() ** ** (The above syntax actually invokes the overloaded parameterless form of
* *execute
, which calls this form with its default parameter values.) * To run just the test named"my favorite test"
in a suite from the Scala interpreter, you would write: ** scala> (new ExampleSuite).execute("my favorite test") ** ** Or: *
* ** scala> (new ExampleSuite).execute(testName = "my favorite test") ** ** The
* *configMap
parameter ** If you provide a value for the
* *configMap
parameter, this method will pass it torun
. If not, the default value * of an emptyMap
will be passed. For more information on how to use a config map to configure your test suites, see * the config map section in the main documentation for this trait. Here's an example in which you configure * a run with the name of an input file: ** scala> (new ExampleSuite).execute(configMap = Map("inputFileName" -> "in.txt") ** ** The
* *color
parameter ** If you leave the
* *color
parameter unspecified, this method will configure the reporter it passes torun
to print * to the standard output in color (via ansi escape characters). If you don't want color output, specify false forcolor
, like this: ** scala> (new ExampleSuite).execute(color = false) ** ** The
* *durations
parameter ** If you leave the
* *durations
parameter unspecified, this method will configure the reporter it passes torun
to * not print durations for tests and suites to the standard output. If you want durations printed, specify true fordurations
, * like this: ** scala> (new ExampleSuite).execute(durations = true) ** ** The
* *shortstacks
andfullstacks
parameters ** If you leave both the
* *shortstacks
andfullstacks
parameters unspecified, this method will configure the reporter * it passes torun
to not print stack traces for failed tests if it has a stack depth that identifies the offending * line of test code. If you prefer a short stack trace (10 to 15 stack frames) to be printed with any test failure, specify true for *shortstacks
: ** scala> (new ExampleSuite).execute(shortstacks = true) ** ** For full stack traces, set
* *fullstacks
to true: ** scala> (new ExampleSuite).execute(fullstacks = true) ** ** If you specify true for both
* *shortstacks
andfullstacks
, you'll get full stack traces. ** The
* *stats
parameter ** If you leave the
* *stats
parameter unspecified, this method will not fireRunStarting
and eitherRunCompleted
* orRunAborted
events to the reporter it passes torun
. * If you specify true forstats
, this method will fire the run events to the reporter, and the reporter will print the * expected test count before the run, and various statistics after, including the number of suites completed and number of tests that * succeeded, failed, were ignored or marked pending. Here's how you get the stats: ** scala> (new ExampleSuite).execute(stats = true) ** * ** To summarize, this method will pass to
*run
: **
* *testName
-None
if this method'stestName
parameter is left at its default value ofnull
, elseSome(testName)
. *- *
reporter
- a reporter that prints to the standard output- *
stopper
- aStopper
whoseapply
method always returnsfalse
- *
filter
- aFilter
constructed withNone
fortagsToInclude
andSet()
* fortagsToExclude
- *
configMap
- theconfigMap
passed to this method- *
distributor
-None
- *
tracker
- a newTracker
* Note: In ScalaTest, the terms "execute" and "run" basically mean the same thing and * can be used interchangably. The reason this method isn't named
* *run
is that it takes advantage of * default arguments, and you can't mix overloaded methods and default arguments in Scala. (If namedrun
, * this method would have the same name but different arguments than the mainrun
method that * takes seven arguments. Thus it would overload and couldn't be used with default argument values.) ** Design note: This method has two "features" that may seem unidiomatic. First, the default value of
* *testName
isnull
. * Normally in Scala the type oftestName
would beOption[String]
and the default value would * beNone
, as it is in this trait'srun
method. Thenull
value is used here for two reasons. First, in * ScalaTest 1.5,execute
was changed from four overloaded methods to one method with default values, taking advantage of * the default and named parameters feature introduced in Scala 2.8. * To not break existing source code,testName
needed to have typeString
, as it did in two of the overloaded *execute
methods prior to 1.5. The other reason is thatexecute
has always been designed to be called primarily * from an interpeter environment, such as the Scala REPL (Read-Evaluate-Print-Loop). In an interpreter environment, minimizing keystrokes is king. * AString
type with anull
default value lets users typesuite.execute("my test name")
rather than *suite.execute(Some("my test name"))
, saving several keystrokes. ** The second non-idiomatic feature is that
* * @param testName the name of one test to run. * @param configMap ashortstacks
andfullstacks
are all lower case rather than * camel case. This is done to be consistent with theShell
, which also uses those forms. The reason * lower case is used in theShell
is to save keystrokes in an interpreter environment. Most Unix commands, for * example, are all lower case, making them easier and quicker to type. In the ScalaTest *Shell
, methods likeshortstacks
,fullstacks
, andnostats
, etc., are * designed to be all lower case so they feel more like shell commands than methods. *Map
of key-value pairs that can be used by the executingSuite
of tests. * @param color a boolean that configures whether output is printed in color * @param durations a boolean that configures whether test and suite durations are printed to the standard output * @param shortstacks a boolean that configures whether short stack traces should be printed for test failures * @param fullstacks a boolean that configures whether full stack traces should be printed for test failures * @param stats a boolean that configures whether test and suite statistics are printed to the standard output * * @throws NullArgumentException if the passedconfigMap
parameter isnull
. * @throws IllegalArgumentException iftestName
is defined, but no test with the specified test name * exists in thisSuite
*/ final def execute( testName: String = null, configMap: ConfigMap = ConfigMap.empty, color: Boolean = true, durations: Boolean = false, shortstacks: Boolean = false, fullstacks: Boolean = false, stats: Boolean = false ): Unit = { requireNonNull(configMap) val SelectedTag = "Selected" val SelectedSet = Set(SelectedTag) val desiredTests: Set[String] = if (testName == null) Set.empty else { testNames.filter { s => s.indexOf(testName) >= 0 || NameTransformer.decode(s).indexOf(testName) >= 0 } } if (testName != null && desiredTests.isEmpty) throw new IllegalArgumentException(Resources.testNotFound(testName)) val dispatch = new DispatchReporter(List(new StandardOutReporter(durations, color, shortstacks, fullstacks, false, false, false, false, false, false, false))) val tracker = new Tracker val filter = if (testName == null) Filter() else { val taggedTests: Map[String, Set[String]] = desiredTests.map(_ -> SelectedSet).toMap Filter( tagsToInclude = Some(SelectedSet), excludeNestedSuites = true, dynaTags = DynaTags(Map.empty, Map(suiteId -> taggedTests)) ) } val suiteClassName = getSuiteClassName(thisSuite) val runStartTime = System.currentTimeMillis if (stats) dispatch(RunStarting(tracker.nextOrdinal(), expectedTestCount(filter), configMap)) val suiteStartTime = System.currentTimeMillis def dispatchSuiteAborted(e: Throwable): Unit = { val eMessage = e.getMessage val rawString = if (eMessage != null && eMessage.length > 0) Resources.runOnSuiteException else Resources.runOnSuiteExceptionWithMessage(eMessage) val formatter = formatterForSuiteAborted(thisSuite, rawString) val duration = System.currentTimeMillis - suiteStartTime dispatch(SuiteAborted(tracker.nextOrdinal(), rawString, thisSuite.suiteName, thisSuite.suiteId, Some(suiteClassName), Some(e), Some(duration), formatter, Some(SeeStackDepthException))) } try { val formatter = formatterForSuiteStarting(thisSuite) dispatch(SuiteStarting(tracker.nextOrdinal(), thisSuite.suiteName, thisSuite.suiteId, Some(suiteClassName), formatter, Some(getTopOfClass(thisSuite)))) val status = run( None, Args(dispatch, Stopper.default, filter, configMap, None, tracker, Set.empty) ) status.waitUntilCompleted() val suiteCompletedFormatter = formatterForSuiteCompleted(thisSuite) val duration = System.currentTimeMillis - suiteStartTime dispatch(SuiteCompleted(tracker.nextOrdinal(), thisSuite.suiteName, thisSuite.suiteId, Some(suiteClassName), Some(duration), suiteCompletedFormatter, Some(getTopOfClass(thisSuite)))) if (stats) { val duration = System.currentTimeMillis - runStartTime dispatch(RunCompleted(tracker.nextOrdinal(), Some(duration))) } } catch { case e: InstantiationException => dispatchSuiteAborted(e) dispatch(RunAborted(tracker.nextOrdinal(), Resources.cannotInstantiateSuite(e.getMessage), Some(e), Some(System.currentTimeMillis - runStartTime))) case e: IllegalAccessException => dispatchSuiteAborted(e) dispatch(RunAborted(tracker.nextOrdinal(), Resources.cannotInstantiateSuite(e.getMessage), Some(e), Some(System.currentTimeMillis - runStartTime))) case e: NoClassDefFoundError => dispatchSuiteAborted(e) dispatch(RunAborted(tracker.nextOrdinal(), Resources.cannotLoadClass(e.getMessage), Some(e), Some(System.currentTimeMillis - runStartTime))) case e: Throwable => dispatchSuiteAborted(e) dispatch(RunAborted(tracker.nextOrdinal(), Resources.bigProblems(e), Some(e), Some(System.currentTimeMillis - runStartTime))) if (!NonFatal(e)) throw e } finally { dispatch.dispatchDisposeAndWaitUntilDone() } } // SKIP-SCALATESTJS,NATIVE-END /** * AMap
whose keys areString
names of tests that are tagged and * whose associated values are theSet
of tag names for the test. If a test has no associated tags, its name * does not appear as a key in the returnedMap
. If thisSuite
contains no tests with tags, this * method returns an emptyMap
. * ** This trait's implementation of this method uses Java reflection to discover any Java annotations attached to its test methods. The * fully qualified name of each unique annotation that extends
* *TagAnnotation
is considered a tag. This trait's * implementation of this method, therefore, places one key/value pair into to the *Map
for each test for which a tag annotation is discovered through reflection. ** In addition to test methods annotations, this trait's implementation will also auto-tag test methods with class level annotations. * For example, if you annotate @Ignore at the class level, all test methods in the class will be auto-annotated with @Ignore. *
* ** Subclasses may override this method to define and/or discover tags in a custom manner, but overriding method implementations * should never return an empty
*/ def tags: Map[String, Set[String]] = Map.empty /** * ASet
as a value. If a test has no tags, its name should not appear as a key in the * returnedMap
. *Set
of test names. If thisSuite
contains no tests, this method returns an emptySet
. * ** This trait's implementation of this method returns an empty
Set
. */ def testNames: Set[String] = Set.empty /* Old style method names will have (Informer) at the end still, but new ones will not. This method will find the one without a Rep if the same name is used with and without a Rep. private[scalatest] def getMethodForTestName(theSuite: Suite, testName: String): Method = try { theSuite.getClass.getMethod( simpleNameForTest(testName), (if (testMethodTakesAnInformer(testName)) Array(classOf[Informer]) else new Array[Class[_]](0)): _* ) } catch { case e: NoSuchMethodException => // Try (Rep) on the end try { theSuite.getClass.getMethod(simpleNameForTest(testName), classOf[Rep]) } catch { case e: NoSuchMethodException => throw new IllegalArgumentException(Resources.testNotFound(testName)) } case e: Throwable => throw e } */ /** * Run a test. * ** This trait's implementation of this method simply returns
* * @param testName the name of one test to run. * @param args theSucceededStatus
* and has no other effect. *Args
for this run * @return aStatus
object that indicates when the test started by this method has completed, and whether or not it failed . * * @throws NullArgumentException if any oftestName
orargs
isnull
. * @throws IllegalArgumentException iftestName
is defined, but no test with the specified test name * exists in thisSuite
*/ protected def runTest(testName: String, args: Args): Status = SucceededStatus /** * Run zero to many of thisSuite
's tests. * ** This method takes a
* *testName
parameter that optionally specifies a test to invoke. * IftestName
is defined, this trait's implementation of this method * invokesrunTest
on this object, passing in: **
* *- *
testName
- theString
value of thetestName
Option
passed * to this method- *
reporter
- theReporter
passed to this method, or one that wraps and delegates to it- *
stopper
- theStopper
passed to this method, or one that wraps and delegates to it- *
configMap
- theconfigMap
Map
passed to this method, or one that wraps and delegates to it* This method takes a
Filter
, which encapsulates an optionalSet
of tag names that should be included * (tagsToInclude
) and aSet
that should be excluded (tagsToExclude
), when deciding which * of thisSuite
's tests to run. * IftagsToInclude
isNone
, all tests will be run * except those those belonging to tags listed in thetagsToExclude
Set
. IftagsToInclude
is defined, only tests * belonging to tags mentioned in thetagsToInclude
Set
, and not mentioned in thetagsToExclude
SettestName
is defined,tagsToInclude
andtagsToExclude
are essentially ignored. * Only iftestName
isNone
willtagsToInclude
andtagsToExclude
be consulted to * determine which of the tests named in thetestNames
Set
should be run. This trait's implementation * behaves this way, and it is part of the general contract of this method, so all overridden forms of this method should behave * this way as well. For more information on test tags, see the main documentation for this trait and for classFilter
. * Note that this means that even if a test is marked as ignored, for example a test method in aSuite
annotated with *org.scalatest.Ignore
, if that test name is passed astestName
torunTest
, it will be invoked * despite theIgnore
annotation. * * ** If
* *testName
isNone
, this trait's implementation of this method * invokestestNames
on thisSuite
to get aSet
of names of tests to potentially run. * (AtestNames
value ofNone
essentially acts as a wildcard that means all tests in * thisSuite
that are selected bytagsToInclude
andtagsToExclude
should be run.) * For each test in thetestName
Set
, in the order * they appear in the iterator obtained by invoking theelements
method on theSet
, this trait's implementation * of this method checks whether the test should be run based on theFilter
. * If so, this implementation invokesrunTest
, passing in: *
-
*
testName
- theString
name of the test to run (which will be one of the names in thetestNames
Set
)
* reporter
- theReporter
passed to this method, or one that wraps and delegates to it
* stopper
- theStopper
passed to this method, or one that wraps and delegates to it
* configMap
- theconfigMap
passed to this method, or one that wraps and delegates to it
*
* If a test is marked with the org.scalatest.Ignore
tag, implementations
* of this method are responsible for ensuring a TestIgnored
event is fired for that test
* and that runTest
is not called for that test.
*
None
, all relevant tests should be run.
* I.e., None
acts like a wildcard that means run all relevant tests in this Suite
.
* @param args the Args
for this run
* @return a Status
object that indicates when all tests started by this method have completed, and whether or not a failure occurred.
*
* @throws NullArgumentException if any of the passed parameters is null
.
* @throws IllegalArgumentException if testName
is defined, but no test with the specified test name
* exists in this Suite
*/
protected def runTests(testName: Option[String], args: Args): Status = {
requireNonNull(testName, args)
import args._
val theTestNames = testNames
// Wrap any non-DispatchReporter, non-CatchReporter in a CatchReporter,
// so that exceptions are caught and transformed
// into error messages on the standard error stream.
val report = wrapReporterIfNecessary(thisSuite, reporter)
val newArgs = args.copy(reporter = report)
val statusBuffer = new ListBuffer[Status]()
// If a testName is passed to run, just run that, else run the tests returned
// by testNames.
testName match {
case Some(tn) =>
val (filterTest, ignoreTest) = filter(tn, tags, suiteId)
if (!filterTest) {
if (ignoreTest)
reportTestIgnored(thisSuite, report, tracker, tn, tn, getEscapedIndentedTextForTest(tn, 1, true), Some(getTopOfMethod(thisSuite, tn)))
else
statusBuffer += runTest(tn, newArgs)
}
case None =>
for ((tn, ignoreTest) <- filter(theTestNames, tags, suiteId)) {
if (!stopper.stopRequested) {
if (ignoreTest)
reportTestIgnored(thisSuite, report, tracker, tn, tn, getEscapedIndentedTextForTest(tn, 1, true), Some(getTopOfMethod(thisSuite, tn)))
else
statusBuffer += runTest(tn, newArgs)
}
}
}
new CompositeStatus(Set.empty ++ statusBuffer)
}
/**
* Runs this suite of tests.
*
* If testName
is None
, this trait's implementation of this method
* calls these two methods on this object in this order:
-
*
runNestedSuites
* runTests
*
* If testName
is defined, then this trait's implementation of this method
* calls runTests
, but does not call runNestedSuites
. This behavior
* is part of the contract of this method. Subclasses that override run
must take
* care not to call runNestedSuites
if testName
is defined. (The
* OneInstancePerTest
trait depends on this behavior, for example.)
*
* Subclasses and subtraits that override this run
method can implement them without
* invoking either the runTests
or runNestedSuites
methods, which
* are invoked by this trait's implementation of this method. It is recommended, but not required,
* that subclasses and subtraits that override run
in a way that does not
* invoke runNestedSuites
also override runNestedSuites
and make it
* final. Similarly it is recommended, but not required,
* that subclasses and subtraits that override run
in a way that does not
* invoke runTests
also override runTests
(and runTest
,
* which this trait's implementation of runTests
calls) and make it
* final. The implementation of these final methods can either invoke the superclass implementation
* of the method, or throw an UnsupportedOperationException
if appropriate. The
* reason for this recommendation is that ScalaTest includes several traits that override
* these methods to allow behavior to be mixed into a Suite
. For example, trait
* BeforeAndAfterEach
overrides runTests
s. In a Suite
* subclass that no longer invokes runTests
from run
, the
* BeforeAndAfterEach
trait is not applicable. Mixing it in would have no effect.
* By making runTests
final in such a Suite
subtrait, you make
* the attempt to mix BeforeAndAfterEach
into a subclass of your subtrait
* a compiler error. (It would fail to compile with a complaint that BeforeAndAfterEach
* is trying to override runTests
, which is a final method in your trait.)
*
None
, all relevant tests should be run.
* I.e., None
acts like a wildcard that means run all relevant tests in this Suite
.
* @param args the Args
for this run
* @return a Status
object that indicates when all tests and nested suites started by this method have completed, and whether or not a failure occurred.
*
* @throws NullArgumentException if any passed parameter is null
.
* @throws IllegalArgumentException if testName
is defined, but no test with the specified test name
* exists in this Suite
*/
def run(testName: Option[String], args: Args): Status = {
requireNonNull(testName, args)
import args._
val originalThreadName = Thread.currentThread.getName
try {
Thread.currentThread.setName(SuiteHelpers.augmentedThreadName(originalThreadName, suiteName))
val report = wrapReporterIfNecessary(thisSuite, reporter)
val newArgs = args.copy(reporter = report)
val nestedSuitesStatus =
testName match {
case None => runNestedSuites(newArgs)
case Some(_) => SucceededStatus
}
val testsStatus = runTests(testName, newArgs)
if (stopper.stopRequested) {
val rawString = Resources.executeStopping
report(InfoProvided(tracker.nextOrdinal(), rawString, Some(NameInfo(thisSuite.suiteName, thisSuite.suiteId, Some(thisSuite.getClass.getName), testName))))
}
new CompositeStatus(Set(nestedSuitesStatus, testsStatus))
}
finally Thread.currentThread.setName(originalThreadName)
}
/**
*
* Run zero to many of this Suite
's nested Suite
s.
*
*
* If the passed distributor
is None
, this trait's
* implementation of this method invokes run
on each
* nested Suite
in the List
obtained by invoking nestedSuites
.
* If a nested Suite
's run
* method completes abruptly with an exception, this trait's implementation of this
* method reports that the Suite
aborted and attempts to run the
* next nested Suite
.
* If the passed distributor
is defined, this trait's implementation
* puts each nested Suite
* into the Distributor
contained in the Some
, in the order in which the
* Suite
s appear in the List
returned by nestedSuites
, passing
* in a new Tracker
obtained by invoking nextTracker
on the Tracker
* passed to this method.
*
* Implementations of this method are responsible for ensuring SuiteStarting
events
* are fired to the Reporter
before executing any nested Suite
, and either SuiteCompleted
* or SuiteAborted
after executing any nested Suite
.
*
Args
for this run
* @return a Status
object that indicates when all nested suites started by this method have completed, and whether or not a failure occurred.
*
* @throws NullArgumentException if any passed parameter is null
.
*/
protected def runNestedSuites(args: Args): Status = {
requireNonNull(args)
import args._
val report = wrapReporterIfNecessary(thisSuite, reporter)
def callExecuteOnSuite(nestedSuite: Suite): Status = {
if (!stopper.stopRequested) {
val rawString = Resources.suiteExecutionStarting
val formatter = formatterForSuiteStarting(nestedSuite)
val suiteClassName = getSuiteClassName(nestedSuite)
val suiteStartTime = System.currentTimeMillis
report(SuiteStarting(tracker.nextOrdinal(), nestedSuite.suiteName, nestedSuite.suiteId, Some(suiteClassName), formatter, Some(TopOfClass(suiteClassName)), nestedSuite.rerunner))
try { // TODO: pass runArgs down and that will get the chosenStyles passed down
// Same thread, so OK to send same tracker
val status = nestedSuite.run(None, Args(report, stopper, filter, configMap, distributor, tracker, Set.empty))
val rawString = Resources.suiteCompletedNormally
val formatter = formatterForSuiteCompleted(nestedSuite)
val duration = System.currentTimeMillis - suiteStartTime
status.unreportedException match {
case Some(ue) =>
report(SuiteAborted(tracker.nextOrdinal(), ue.getMessage, nestedSuite.suiteName, nestedSuite.suiteId, Some(suiteClassName), Some(ue), Some(duration), formatter, Some(SeeStackDepthException), nestedSuite.rerunner))
FailedStatus
case None =>
report(SuiteCompleted(tracker.nextOrdinal(), nestedSuite.suiteName, nestedSuite.suiteId, Some(suiteClassName), Some(duration), formatter, Some(TopOfClass(suiteClassName)), nestedSuite.rerunner))
SucceededStatus
}
}
catch {
case e: RuntimeException => {
val eMessage = e.getMessage
val rawString =
if (eMessage != null && eMessage.length > 0)
Resources.executeExceptionWithMessage(eMessage)
else
Resources.executeException
val formatter = formatterForSuiteAborted(nestedSuite, rawString)
val duration = System.currentTimeMillis - suiteStartTime
report(SuiteAborted(tracker.nextOrdinal(), rawString, nestedSuite.suiteName, nestedSuite.suiteId, Some(suiteClassName), Some(e), Some(duration), formatter, Some(SeeStackDepthException), nestedSuite.rerunner))
if (NonFatal(e.getCause))
FailedStatus
else
throw e.getCause
}
}
}
else
FailedStatus
}
val statusBuffer = new ListBuffer[Status]()
if (!filter.excludeNestedSuites) {
val nestedSuitesArray = nestedSuites.toArray
distributor match {
case None =>
for (nestedSuite <- nestedSuitesArray) {
if (!stopper.stopRequested)
statusBuffer += callExecuteOnSuite(nestedSuite)
}
case Some(distribute) =>
for (nestedSuite <- nestedSuitesArray)
statusBuffer += distribute(nestedSuite, args.copy(tracker = tracker.nextTracker()))
}
}
new CompositeStatus(Set.empty ++ statusBuffer)
}
/**
* A user-friendly suite name for this Suite
.
*
*
* This trait's
* implementation of this method returns the simple name of this object's class. This
* trait's implementation of runNestedSuites
calls this method to obtain a
* name for Report
s to pass to the suiteStarting
, suiteCompleted
,
* and suiteAborted
methods of the Reporter
.
*
Suite
object's suite name.
*/
def suiteName: String = getSimpleNameOfAnObjectsClass(thisSuite)
/**
* A string ID for this Suite
that is intended to be unique among all suites reported during a run.
*
*
* 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 Suite
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 Suite
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 Suite
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.
*
* The suite ID is intended 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. *
* * @return thisSuite
object's ID.
*/
def suiteId: String = thisSuite.getClass.getName
/**
* The total number of tests that are expected to run when this Suite
's run
method is invoked.
*
* * This trait's implementation of this method returns the sum of: *
* *-
*
- the size of the
testNames
List
, minus the number of tests marked as ignored and * any tests that are exluded by the passedFilter
* - the sum of the values obtained by invoking
*
expectedTestCount
on every nestedSuite
contained in *nestedSuites
*
Filter
with which to filter tests to count based on their tags
*/
def expectedTestCount(filter: Filter): Int = {
@tailrec
def countNestedSuiteTests(acc: Int, nestedSuitesToCount: List[Suite], filter: Filter): Int =
nestedSuitesToCount match {
case List() => acc
case head :: tail =>
countNestedSuiteTests(acc + head.expectedTestCount(filter), tail, filter)
}
countNestedSuiteTests(filter.runnableTestCount(testNames, tags, suiteId), nestedSuites.toList, filter)
}
// MOVE IT
private[scalatest] def createCatchReporter(reporter: Reporter): Reporter = new WrapperCatchReporter(reporter)
/**
* The fully qualified class name of the rerunner to rerun this suite. This implementation will look at this.getClass and see if it is
* either an accessible Suite, or it has a WrapWith annotation. If so, it returns the fully qualified class name wrapped in a Some,
* or else it returns None.
*/
def rerunner: Option[String] = {
val suiteClass = getClass
// SKIP-SCALATESTJS,NATIVE-START
val isAccessible = SuiteDiscoveryHelper.isAccessibleSuite(suiteClass)
val hasWrapWithAnnotation = suiteClass.getAnnotation(classOf[WrapWith]) != null
if (isAccessible || hasWrapWithAnnotation)
Some(suiteClass.getName)
else
None
// SKIP-SCALATESTJS,NATIVE-END
//SCALATESTJS,NATIVE-ONLY Some(suiteClass.getName)
}
/**
* The styleName
lifecycle method has been deprecated and will be removed in a future version of ScalaTest.
*
* This method was used to support the chosen styles feature, which was deactivated in 3.1.0. The internal modularization of ScalaTest in 3.2.0
* will replace chosen styles as the tool to encourage consistency across a project. We do not plan a replacement for styleName
.
TestData
instance for the passed test name, given the passed config map.
*
*
* This method is used to obtain a TestData
instance to pass to withFixture(NoArgTest)
* and withFixture(OneArgTest)
and the beforeEach
and afterEach
methods
* of trait BeforeAndAfterEach
.
*
TestData
instance
* @param theConfigMap the config map to include in the returned TestData
* @return a TestData
instance for the specified test, which includes the specified config map
*/
def testDataFor(testName: String, theConfigMap: ConfigMap = ConfigMap.empty): TestData = {
new TestData { // TODO: Document that we return a "null object" here. Seems odd actually, shouldn't this return an Option?
val configMap = theConfigMap
val name = testName
val scopes = Vector.empty
val text = testName
val tags = Set.empty[String]
val pos = None
}
}
}
private[scalatest] object Suite {
val InformerInParens = "(Informer)"
val FixtureAndInformerInParens = "(FixtureParam, Informer)"
val FixtureInParens = "(FixtureParam)"
val IgnoreTagName = "org.scalatest.Ignore"
private[scalatest] val SELECTED_TAG = "org.scalatest.Selected"
private[scalatest] val CHOSEN_STYLES = "org.scalatest.ChosenStyles"
private[scalatest] val defaultTestSortingReporterTimeoutInSeconds = 2.0
// SKIP-SCALATESTJS,NATIVE-START
def checkForPublicNoArgConstructor(clazz: java.lang.Class[_]) = {
try {
val constructor = clazz.getConstructor(new Array[java.lang.Class[_]](0): _*)
Modifier.isPublic(constructor.getModifiers)
}
catch {
case nsme: NoSuchMethodException => false
}
}
// SKIP-SCALATESTJS,NATIVE-END
def diffStrings(s: String, t: String): Tuple2[String, String] = Prettifier.diffStrings(s, t)
// If the objects are two strings, replace them with whatever is returned by diffStrings.
// Otherwise, use the same objects.
def getObjectsForFailureMessage(a: Any, b: Any) = Prettifier.getObjectsForFailureMessage(a, b)
//
// Use MotionToSuppress on aggregator Suites, i.e. Suites that
// contain other Suites but don't contain any tests themselves
// (e.g. DiscoverySuite).
//
def formatterForSuiteStarting(suite: Suite): Option[Formatter] =
if ((suite.testNames.isEmpty) && (suite.nestedSuites.size > 0))
Some(MotionToSuppress)
else
Some(IndentedText(suite.suiteName + ":", suite.suiteName, 0))
def formatterForSuiteCompleted(suite: Suite): Option[Formatter] =
Some(MotionToSuppress)
def formatterForSuiteAborted(suite: Suite, message: String): Option[Formatter] = {
val actualSuiteName =
suite match {
case DeferredAbortedSuite(suiteId, suiteClassName, deferredThrowable) => suiteClassName
case _ => suite.getClass.getName
}
Some(IndentedText(actualSuiteName, message, 0))
}
def getSuiteClassName(suite: Suite): String =
suite match {
case DeferredAbortedSuite(suiteId, suiteClassName, deferredThrowable) => suiteClassName
case _ => suite.getClass.getName
}
/*
def simpleNameForTest(testName: String) =
if (testName.endsWith(InformerInParens))
testName.substring(0, testName.length - InformerInParens.length)
else
testName
*/
def anExceptionThatShouldCauseAnAbort(throwable: Throwable): Boolean =
throwable match {
// SKIP-SCALATESTJS,NATIVE-START
case _: AnnotationFormatError |
/*
_: org.scalatest.TestRegistrationClosedException |
_: org.scalatest.NotAllowedException |
*/
_: CoderMalfunctionError |
_: FactoryConfigurationError |
_: LinkageError |
_: ThreadDeath |
_: TransformerFactoryConfigurationError |
_: VirtualMachineError => true
// Don't use AWTError directly because it doesn't exist on Android, and a user
// got ScalaTest to compile under Android.
case e if e.getClass.getName == "java.awt.AWTError" => true
// SKIP-SCALATESTJS,NATIVE-END
case _ => false
}
def takesInformer(m: Method) = {
val paramTypes = m.getParameterTypes
paramTypes.length == 1 && classOf[Informer].isAssignableFrom(paramTypes(0))
}
def isTestMethodGoodies(m: Method) = {
val isInstanceMethod = !Modifier.isStatic(m.getModifiers())
// name must have at least 4 chars (minimum is "test")
val simpleName = m.getName
val firstFour = if (simpleName.length >= 4) simpleName.substring(0, 4) else ""
val paramTypes = m.getParameterTypes
val hasNoParams = paramTypes.length == 0
// Discover testNames(Informer) because if we didn't it might be confusing when someone
// actually wrote a testNames(Informer) method and it was silently ignored.
val isTestNames = simpleName == "testNames"
val isTestTags = simpleName == "testTags"
val isTestDataFor = (simpleName == "testDataFor" && paramTypes.length == 2 && classOf[String].isAssignableFrom(paramTypes(0)) && classOf[ConfigMap].isAssignableFrom(paramTypes(1))) ||
(simpleName == "testDataFor$default$2" && paramTypes.length == 0)
(isInstanceMethod, simpleName, firstFour, paramTypes, hasNoParams, isTestNames, isTestTags, isTestDataFor)
}
def testMethodTakesAnInformer(testName: String): Boolean = testName.endsWith(InformerInParens)
/*
For info and test names, the formatted text should have one level shaved off so that the text will
line up correctly, and the icon is over to the left of that even with the enclosing level.
If a test is at the top level (not nested inside a describe), it's level is 0. So no need to subtract 1
to make room for the icon in that case. An info inside such a test will have level 1. And agin, in that
case no need to subtract 1. Such a test is "outermost test" and the info inside is "in outermost test" in:
class ArghSpec extends RefSpec with GivenWhenThen {
info("in ArghSpec")
it("outermost test") {
info("in outermost test")
}
describe("Apple") {
info("in Apple")
describe("Boat") {
info("in Boat")
describe("Cat") {
info("in Cat")
describe("Dog") {
info("in Dog")
describe("Elephant") {
info("in Elephant")
it("Factory") {
info("in Factory (test)")
given("an empty Stack")
when("push is invoked")
then("it should have size 1")
and("pop should return the pushed value")
}
}
}
}
}
}
}
It should (and at this point does) output this:
[scalatest] ArghSpec:
[scalatest] + in ArghSpec
[scalatest] - outermost test (5 milliseconds)
[scalatest] + in outermost test
[scalatest] Apple
[scalatest] + in Apple
[scalatest] Boat
[scalatest] + in Boat
[scalatest] Cat
[scalatest] + in Cat
[scalatest] Dog
[scalatest] + in Dog
[scalatest] Elephant
[scalatest] + in Elephant
[scalatest] - Factory (1 millisecond)
[scalatest] + in Factory (test)
[scalatest] + Given an empty Stack
[scalatest] + When push is invoked
[scalatest] + Then it should have size 1
[scalatest] + And pop should return the pushed value
FeatureSpec doesn't want any icons printed out. So adding includeIcon here. It
was already in getIndentedTextForInfo because of descriptions being printed out
without icons.
This should really be named getIndentedTextForTest maybe, because I think it is just
used for test events like succeeded/failed, etc.
*/
def getIndentedTextForTest(testText: String, level: Int, includeIcon: Boolean) = {
val decodedTestText = NameTransformer.decode(testText)
val formattedText =
if (includeIcon) {
val testSucceededIcon = Resources.testSucceededIconChar
(" " * (if (level == 0) 0 else (level - 1))) + Resources.iconPlusShortName(testSucceededIcon, decodedTestText)
}
else {
(" " * level) + decodedTestText
}
IndentedText(formattedText, decodedTestText, level)
}
def getEscapedIndentedTextForTest(testText: String, level: Int, includeIcon: Boolean): IndentedText = {
val decodedTestText = NameTransformer.decode(testText)
val escapedTestText =
if (decodedTestText.startsWith("test: "))
decodedTestText.drop(6)
else
decodedTestText
val formattedText =
if (includeIcon) {
val testSucceededIcon = Resources.testSucceededIconChar
(" " * (if (level == 0) 0 else (level - 1))) + Resources.iconPlusShortName(testSucceededIcon, escapedTestText)
}
else {
(" " * level) + escapedTestText
}
IndentedText(formattedText, decodedTestText, level)
}
// The icon is not included for branch description text, but is included for things sent via info(), given(),
// when(), then(), etc. When it is included, reduce the level by 1, unless it is already 1 or 0.
def getIndentedTextForInfo(message: String, level: Int, includeIcon: Boolean, infoIsInsideATest: Boolean) = {
val formattedText =
if (includeIcon) {
val infoProvidedIcon = Resources.infoProvidedIconChar
//
// Inside a test, you want level 1 to stay 1
// [scalatest] - outermost test (5 milliseconds)
// [scalatest] + in outermost test
//
// But outside a test, level 1 should be transformed to 0
// [scalatest] Apple
// [scalatest] + in Apple
//
val indentationLevel =
level match {
case 0 => 0
case 1 if infoIsInsideATest => 1
case _ => level - 1
}
(" " * indentationLevel) + Resources.iconPlusShortName(infoProvidedIcon, message)
// (" " * (if (level <= 1) level else (level - 1))) + Resources.iconPlusShortName(infoProvidedIcon, message)
}
else {
(" " * level) + message
}
IndentedText(formattedText, message, level)
}
def getMessageForException(e: Throwable): String =
if (e.getMessage != null)
e.getMessage
else
Resources.exceptionThrown(e.getClass.getName) // Say something like, "java.lang.Exception was thrown."
def indentation(level: Int) = " " * level
def indentLines(level: Int, lines: GenTraversable[String]) =
lines.map(line => line.split("\n").map(indentation(level) + _).mkString("\n"))
def substituteHtmlSpace(value: String) = value.replaceAll(" ", " ")
// SKIP-SCALATESTJS,NATIVE-START
def unparsedXml(value: String) = scala.xml.Unparsed(value)
def xmlContent(value: String) = unparsedXml(substituteHtmlSpace(value))
// SKIP-SCALATESTJS,NATIVE-END
def analysisFromThrowable(throwable: Throwable): scala.collection.immutable.IndexedSeq[String] =
throwable match {
case tfe: TestFailedException => tfe.analysis
case _ => Vector.empty
}
def reportTestFailed(theSuite: Suite, report: Reporter, throwable: Throwable, testName: String, testText: String,
recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], rerunnable: Option[String], tracker: Tracker, duration: Long, formatter: Formatter, location: Option[Location]): Unit = {
val message = getMessageForException(throwable)
//val formatter = getEscapedIndentedTextForTest(testText, level, includeIcon)
val payload =
throwable match {
case optPayload: PayloadField =>
optPayload.payload
case _ =>
None
}
report(TestFailed(tracker.nextOrdinal(), message, theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, recordedEvents, analysisFromThrowable(throwable), Some(throwable), Some(duration), Some(formatter), location, theSuite.rerunner, payload))
}
// TODO: Possibly separate these out from method tests and function tests, because locations are different
// Update: Doesn't seems to need separation, to be confirmed with Bill.
def reportTestStarting(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, rerunnable: Option[String], location: Option[Location]): Unit = {
report(TestStarting(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, Some(MotionToSuppress),
location, rerunnable))
}
def reportTestPending(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], duration: Long, formatter: Formatter, location: Option[Location]): Unit = {
report(TestPending(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, recordedEvents, Some(duration), Some(formatter),
location))
}
/*
def reportTestCanceled(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, duration: Long, formatter: Formatter, location: Option[Location]) {
val message = getMessageForException(throwable)
report(TestCanceled(tracker.nextOrdinal(), message, theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, Some(duration), Some(formatter),
location))
}
*/
def reportTestCanceled(theSuite: Suite, report: Reporter, throwable: Throwable, testName: String, testText: String,
recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], rerunnable: Option[String], tracker: Tracker, duration: Long, formatter: Formatter, location: Option[Location]): Unit = {
val message = getMessageForException(throwable)
val payload =
throwable match {
case optPayload: PayloadField =>
optPayload.payload
case _ =>
None
}
//val formatter = getEscapedIndentedTextForTest(testText, level, includeIcon)
report(TestCanceled(tracker.nextOrdinal(), message, theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, recordedEvents, Some(throwable), Some(duration), Some(formatter), location, rerunnable, payload))
}
def reportTestSucceeded(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], duration: Long, formatter: Formatter, rerunnable: Option[String], location: Option[Location]): Unit = {
report(TestSucceeded(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, recordedEvents, Some(duration), Some(formatter),
location, rerunnable))
}
def reportTestIgnored(theSuite: Suite, report: Reporter, tracker: Tracker, testName: String, testText: String, formatter: Formatter, location: Option[Location]): Unit = {
val testSucceededIcon = Resources.testSucceededIconChar
report(TestIgnored(tracker.nextOrdinal(), theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName, testText, Some(formatter),
location))
}
def createInfoProvided(theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true) = {
InfoProvided(
tracker.nextOrdinal(),
message,
if (includeNameInfo)
Some(NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName))
else
None,
None,
Some(getIndentedTextForInfo(message, level, includeIcon, testName.isDefined)),
location,
payload
)
}
def createNoteProvided(theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true) = {
NoteProvided(
tracker.nextOrdinal(),
message,
if (includeNameInfo)
Some(NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName))
else
None,
None,
Some(getIndentedTextForInfo(message, level, includeIcon, testName.isDefined)),
location,
payload
)
}
def createAlertProvided(theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true) = {
AlertProvided(
tracker.nextOrdinal(),
message,
if (includeNameInfo)
Some(NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName))
else
None,
None,
Some(getIndentedTextForInfo(message, level, includeIcon, testName.isDefined)),
location,
payload
)
}
// If not fired in the context of a test, then testName will be None
def reportInfoProvided(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true
): Unit = {
report(
createInfoProvided(
theSuite,
report,
tracker,
testName,
message,
payload,
level,
location,
includeNameInfo,
includeIcon
)
)
}
def reportNoteProvided(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true
): Unit = {
report(
createNoteProvided(
theSuite,
report,
tracker,
testName,
message,
payload,
level,
location,
includeNameInfo,
includeIcon
)
)
}
def reportAlertProvided(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
payload: Option[Any],
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true
): Unit = {
report(
createAlertProvided(
theSuite,
report,
tracker,
testName,
message,
payload,
level,
location,
includeNameInfo,
includeIcon
)
)
}
def createMarkupProvided(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true
) = {
MarkupProvided(
tracker.nextOrdinal(),
message,
if (includeNameInfo)
Some(NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), testName))
else
None,
Some(getIndentedTextForInfo(message, level, includeIcon, testName.isDefined)),
location
)
}
// If not fired in the context of a test, then testName will be None
def reportMarkupProvided(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
testName: Option[String],
message: String,
level: Int,
location: Option[Location],
includeNameInfo: Boolean,
includeIcon: Boolean = true
): Unit = {
report(
createMarkupProvided(
theSuite,
report,
tracker,
testName,
message,
level,
location,
includeNameInfo
)
)
}
// If not fired in the context of a test, then testName will be None
def reportScopeOpened(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
message: String,
level: Int,
includeIcon: Boolean = true,
location: Option[Location]
): Unit = {
report(
ScopeOpened(
tracker.nextOrdinal(),
message,
NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), None),
Some(getIndentedTextForInfo(message, level, includeIcon, false)),
location
)
)
}
// If not fired in the context of a test, then testName will be None
def reportScopeClosed(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
message: String,
level: Int,
includeIcon: Boolean = true,
location: Option[Location]
): Unit = {
report(
ScopeClosed(
tracker.nextOrdinal(),
message,
NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), None),
Some(MotionToSuppress),
location
)
)
}
def reportScopePending(
theSuite: Suite,
report: Reporter,
tracker: Tracker,
message: String,
level: Int,
includeIcon: Boolean = true,
location: Option[Location]
): Unit = {
report(
ScopePending(
tracker.nextOrdinal(),
message,
NameInfo(theSuite.suiteName, theSuite.suiteId, Some(theSuite.getClass.getName), None),
Some(getIndentedTextForInfo(message, level, includeIcon, false)),
location
)
)
}
/*def getLineInFile(stackTraceList:List[StackTraceElement], sourceFileName:String, methodName: String):Option[LineInFile] = {
val baseStackDepth = stackTraceList.takeWhile(stackTraceElement => sourceFileName != stackTraceElement.getFileName || stackTraceElement.getMethodName != methodName).length
val stackTraceOpt = stackTraceList.drop(baseStackDepth).find(stackTraceElement => stackTraceElement.getMethodName() == "