All Downloads are FREE. Search and download functionalities are using the official Maven repository.

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

/*
 * 

Using info and markup

* *

* One of the parameters to Suite's run method is a Reporter, 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 the Reporter as the suite runs. * Most often the reporting done by default will be sufficient, but * occasionally you may wish to provide custom information to the Reporter from a test. * For this purpose, an Informer that will forward information * to the current Reporter is provided via the info parameterless method. * You can pass the extra information to the Informer via its apply method. * The Informer will then pass the information to the Reporter via an InfoProvided event. * Here's an example that shows both a direct use as well as an indirect use through the methods * of GivenWhenThen: *

* *
 * 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 this Suite 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 a Documenter named markup, which * you can use to transmit markup text to the Reporter. *

* -------------- *

Assertions and ===

* *

* Inside test methods in a Suite, you can write assertions by invoking assert and passing in a Boolean expression, * such as: *

* *
 * val left = 2
 * val right = 1
 * assert(left == right)
 * 
* *

* If the passed expression is true, assert will return normally. If false, * assert will complete abruptly with a TestFailedException. This exception is usually not caught * by the test method, which means the test method itself will complete abruptly by throwing the TestFailedException. 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 to assert, a failed assertion will be reported, but without * reporting the left and right values. You can alternatively encode these values in a String passed as * a second argument to assert, 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 trait Assertions which trait Suite 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 thrown TestFailedException from the assert * 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 ScalaTest Suite where you'd use assertEquals in a JUnit TestCase. * The === operator is made possible by an implicit conversion from Any * to Equalizer. If you're curious to understand the mechanics, see the documentation for * Equalizer and the convertToEqualizer method. *

* *

Expected results

* * Although === provides a natural, readable extension to Scala's assert 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 called left and right, * because if one were named expected and the other actual, it would be difficult for people to * remember which was which. To help with these limitations of assertions, Suite includes a method called assertResult that * can be used as an alternative to assert with ===. To use assertResult, you place * the expected value in parentheses after assertResult, 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 is a - b. This expectation will fail, and * the detail message in the TestFailedException 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 throws IndexOutOfBoundsException 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. The fail method always completes abruptly with * a TestFailedException, 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 of IndexOutOfBoundsException, * intercept will return that exception. But if charAt completes normally, or throws a different * exception, intercept will complete abruptly with a TestFailedException. The intercept 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 * trait MustMatchers. *

* *

* 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 assertEquals * 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.) *

*/ /** * A suite of tests. A 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 other Suites, * which are called nested Suites. Those nested Suites can in turn have * their own nested Suites, and so on. Large test suites can be organized, therefore, as a tree of * nested Suites. * This trait's run method, in addition to invoking its * test methods, invokes run on each of its nested Suites. *

* *

* A List of a Suite's nested Suites can be obtained by invoking its * nestedSuites method. If you wish to create a Suite that serves as a * container for nested Suites, whether or not it has test methods of its own, simply override nestedSuites * to return a List of the nested Suites. Because this is a common use case, ScalaTest provides * a convenience Suites class, which takes a variable number of nested Suites 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 discover Suites automatically, so you need not * necessarily define nested Suites explicitly. See the documentation * for Runner 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 a ConfigMap. * 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 to run, runNestedSuites, runTests, and runTest, * 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 the NoArgTest passed to withFixture, or the OneArgTest passed to * withFixture in the traits in the org.scalatest.fixture package. (See the * documentation for FixtureSuite * 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 optional Distributor. If * a Distributor is passed in, this trait's implementation of run puts its nested * Suites into the distributor rather than executing them directly. The caller of run * is responsible for ensuring that some entity runs the Suites placed into the * distributor. The -P command line parameter to Runner, for example, will cause * Suites put into the Distributor to be run in parallel via a pool of threads. * If you wish to execute the tests themselves in parallel, mix in ParallelTestExecution. *

* * *

"Run-aborting" exceptions

* *

* The Javadoc documentation for java.lang.Error states: *

* *
* An Error is a subclass of Throwable that indicates serious problems that a reasonable application * should not try to catch. Most * such errors are abnormal conditions. *
* *

* Because Errors are used to denote serious errors, trait Suite and its subtypes in the ScalaTest API * do not always treat a test that completes abruptly with an Error 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 uses Errors 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 Errors that exist as part of Java 1.5 API, excluding java.lang.AssertionError. * ScalaTest does treat a thrown AssertionError 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 the Suite 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 to Errors, * this behavior is not required by the contract of Suite. Subclasses and subtraits that you define, for example, may treat all * Errors 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 the Suite's test names in a custom way.
  • *
  • tags - override this method to specify the Suite's test tags in a custom way.
  • *
  • nestedSuites - override this method to specify the Suite's nested Suites in a custom way.
  • *
  • suiteName - override this method to specify the Suite's name in a custom way.
  • *
  • expectedTestCount - override this method to count this Suite's expected tests in a custom way.
  • *
* *

* For example, this trait's implementation of testNames performs reflection to discover methods starting with test, * and places these in a Set whose iterator returns the names in alphabetical order. If you wish to run tests in a different * order in a particular Suite, perhaps because a test named testAlpha can only succeed after a test named * testBeta has run, you can override testNames so that it returns a Set whose iterator returns * testBeta before testAlpha. (This trait's implementation of run will invoke tests * in the order they come out of the testNames 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 override testNames to discover tests using either of these two APIs * @Test annotations, or one of your own invention. (This is in fact * how org.scalatest.junit.JUnitSuite and org.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 overrides testNames, runTest, and run 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 org.scalatest.junit and org.scalatest.testng exist to make this easy. * No matter what legacy tests you may have, it is likely you can create or use an existing Suite 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. *

* * @author Bill Venners */ trait Suite extends Assertions with Serializable { thisSuite => import Suite.InformerInParens /** * An immutable IndexedSeq of this Suite object's nested Suites. If this Suite contains no nested Suites, * this method returns an empty IndexedSeq. This trait's implementation of this method returns an empty List. */ def nestedSuites: collection.immutable.IndexedSeq[Suite] = Vector.empty // SKIP-SCALATESTJS,NATIVE-START /** * Executes one or more tests in this Suite, 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 (of null), this method will pass None to * the testName parameter of run, and as a result all the tests in this suite will be executed. If you * specify a testName, this method will pass Some(testName) to run, 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 to run. If not, the default value * of an empty Map 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 to run to print * to the standard output in color (via ansi escape characters). If you don't want color output, specify false for color, 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 to run to * not print durations for tests and suites to the standard output. If you want durations printed, specify true for durations, * like this: *

* *
   * scala> (new ExampleSuite).execute(durations = true)
   * 
* *

* The shortstacks and fullstacks parameters *

* *

* If you leave both the shortstacks and fullstacks parameters unspecified, this method will configure the reporter * it passes to run 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 and fullstacks, you'll get full stack traces. *

* *

* The stats parameter *

* *

* If you leave the stats parameter unspecified, this method will not fire RunStarting and either RunCompleted * or RunAborted events to the reporter it passes to run. * If you specify true for stats, 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's testName parameter is left at its default value of null, else Some(testName). *
  • reporter - a reporter that prints to the standard output
  • *
  • stopper - a Stopper whose apply method always returns false
  • *
  • filter - a Filter constructed with None for tagsToInclude and Set() * for tagsToExclude
  • *
  • configMap - the configMap passed to this method
  • *
  • distributor - None
  • *
  • tracker - a new Tracker
  • *
* *

* 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 named run, * this method would have the same name but different arguments than the main run 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 is null. * Normally in Scala the type of testName would be Option[String] and the default value would * be None, as it is in this trait's run method. The null 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 type String, as it did in two of the overloaded * execute methods prior to 1.5. The other reason is that execute 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. * A String type with a null default value lets users type suite.execute("my test name") rather than * suite.execute(Some("my test name")), saving several keystrokes. *

* *

* The second non-idiomatic feature is that shortstacks and fullstacks are all lower case rather than * camel case. This is done to be consistent with the Shell, which also uses those forms. The reason * lower case is used in the Shell 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 like shortstacks, fullstacks, and nostats, etc., are * designed to be all lower case so they feel more like shell commands than methods. *

* * @param testName the name of one test to run. * @param configMap a Map of key-value pairs that can be used by the executing Suite 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 passed configMap parameter is null. * @throws IllegalArgumentException if testName is defined, but no test with the specified test name * exists in this Suite */ 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 /** * A Map whose keys are String names of tests that are tagged and * whose associated values are the Set of tag names for the test. If a test has no associated tags, its name * does not appear as a key in the returned Map. If this Suite contains no tests with tags, this * method returns an empty Map. * *

* 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 Set as a value. If a test has no tags, its name should not appear as a key in the * returned Map. *

*/ def tags: Map[String, Set[String]] = Map.empty /** * A Set of test names. If this Suite contains no tests, this method returns an empty Set. * *

* 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 SucceededStatus * and has no other effect. *

* * @param testName the name of one test to run. * @param args the Args for this run * @return a Status object that indicates when the test started by this method has completed, and whether or not it failed . * * @throws NullArgumentException if any of testName or args is null. * @throws IllegalArgumentException if testName is defined, but no test with the specified test name * exists in this Suite */ protected def runTest(testName: String, args: Args): Status = SucceededStatus /** * Run zero to many of this Suite's tests. * *

* This method takes a testName parameter that optionally specifies a test to invoke. * If testName is defined, this trait's implementation of this method * invokes runTest on this object, passing in: *

* *
    *
  • testName - the String value of the testName Option passed * to this method
  • *
  • reporter - the Reporter passed to this method, or one that wraps and delegates to it
  • *
  • stopper - the Stopper passed to this method, or one that wraps and delegates to it
  • *
  • configMap - the configMap Map passed to this method, or one that wraps and delegates to it
  • *
* *

* This method takes a Filter, which encapsulates an optional Set of tag names that should be included * (tagsToInclude) and a Set that should be excluded (tagsToExclude), when deciding which * of this Suite's tests to run. * If tagsToInclude is None, all tests will be run * except those those belonging to tags listed in the tagsToExclude Set. If tagsToInclude is defined, only tests * belonging to tags mentioned in the tagsToInclude Set, and not mentioned in the tagsToExcludeSet * will be run. However, if testName is defined, tagsToInclude and tagsToExclude are essentially ignored. * Only if testName is None will tagsToInclude and tagsToExclude be consulted to * determine which of the tests named in the testNames 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 class Filter. * Note that this means that even if a test is marked as ignored, for example a test method in a Suite annotated with * org.scalatest.Ignore, if that test name is passed as testName to runTest, it will be invoked * despite the Ignore annotation. *

* *

* If testName is None, this trait's implementation of this method * invokes testNames on this Suite to get a Set of names of tests to potentially run. * (A testNames value of None essentially acts as a wildcard that means all tests in * this Suite that are selected by tagsToInclude and tagsToExclude should be run.) * For each test in the testName Set, in the order * they appear in the iterator obtained by invoking the elements method on the Set, this trait's implementation * of this method checks whether the test should be run based on the Filter. * If so, this implementation invokes runTest, passing in: *

* *
    *
  • testName - the String name of the test to run (which will be one of the names in the testNames Set)
  • *
  • reporter - the Reporter passed to this method, or one that wraps and delegates to it
  • *
  • stopper - the Stopper passed to this method, or one that wraps and delegates to it
  • *
  • configMap - the configMap 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. *

* * @param testName an optional name of one test to run. If 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:

* *
    *
  1. runNestedSuites
  2. *
  3. runTests
  4. *
* *

* 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 runTestss. 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.) *

* * @param testName an optional name of one test to run. If 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 Suites. * *

* 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 * Suites 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. *

* * @param args the 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 Reports to pass to the suiteStarting, suiteCompleted, * and suiteAborted methods of the Reporter. *

* * @return this 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 this Suite 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 passed Filter
  • *
  • the sum of the values obtained by invoking * expectedTestCount on every nested Suite contained in * nestedSuites
  • *
* * @param filter a 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.

*/ @deprecated("The styleName lifecycle method has been deprecated and will be removed in a future version of ScalaTest with no replacement.", "3.1.0") val styleName: String = "org.scalatest.Suite" /** * Provides a 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. *

* * @param testName the name of the test for which to return a 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() == "") stackTraceOpt match { case Some(stackTrace) => Some(LineInFile(stackTrace.getLineNumber, stackTrace.getFileName)) case None => None } }*/ def getLineInFile(stackTraceList: Array[StackTraceElement], stackDepth: Int) = { if(stackDepth >= 0 && stackDepth < stackTraceList.length) { val stackTrace = stackTraceList(stackDepth) if(stackTrace.getLineNumber >= 0 && stackTrace.getFileName != null) Some(LineInFile(stackTrace.getLineNumber, getFailedCodeFileName(stackTrace).getOrElse(""), None)) else None } else None } def autoTagClassAnnotations(tags: Map[String, Set[String]], theSuite: Suite) = { // SKIP-SCALATESTJS,NATIVE-START val suiteTags = for { a <- theSuite.getClass.getAnnotations annotationClass = a.annotationType if annotationClass.isAnnotationPresent(classOf[TagAnnotation]) } yield annotationClass.getName val autoTestTags = if (suiteTags.size > 0) Map() ++ theSuite.testNames.map(tn => (tn, suiteTags.toSet)) else Map.empty[String, Set[String]] mergeMap[String, Set[String]](List(tags, autoTestTags)) ( _ ++ _ ) // SKIP-SCALATESTJS,NATIVE-END //SCALATESTJS,NATIVE-ONLY tags } def handleFailedTest( theSuite: Suite, throwable: Throwable, testName: String, recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], report: Reporter, tracker: Tracker, formatter: Formatter, duration: Long ): Unit = { val message = getMessageForException(throwable) //val formatter = getEscapedIndentedTextForTest(testName, 1, true) 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, testName, recordedEvents, analysisFromThrowable(throwable), Some(throwable), Some(duration), Some(formatter), Some(SeeStackDepthException), theSuite.rerunner, payload)) } // SKIP-SCALATESTJS,NATIVE-START def getTopOfClass(theSuite: Suite) = TopOfClass(getSuiteClassName(theSuite)) def getTopOfMethod(theSuite: Suite, method: Method) = TopOfMethod(getSuiteClassName(theSuite), method.toGenericString()) def getTopOfMethod(theSuite: Suite, testName: String) = TopOfMethod(getSuiteClassName(theSuite), getMethodForTestName(theSuite, testName).toGenericString()) // Factored out to share this with FixtureSuite.runTest def getSuiteRunTestGoodies(theSuite: Suite, stopper: Stopper, reporter: Reporter, testName: String): (Stopper, Reporter, Method, Long) = { val (theStopper, report, testStartTime) = getRunTestGoodies(theSuite, stopper, reporter, testName) val method = getMethodForTestName(theSuite, testName) (theStopper, report, method, testStartTime) } // SKIP-SCALATESTJS,NATIVE-END //SCALATESTJS,NATIVE-ONLY def getTopOfMethod(theSuite: Suite, testName: String) = TopOfMethod(theSuite.getClass.getName, "test" + testName.capitalize) // Sharing this with FunSuite and fixture.FunSuite as well as Suite and FixtureSuite def getRunTestGoodies(theSuite: Suite, stopper: Stopper, reporter: Reporter, testName: String): (Stopper, Reporter, Long) = { val report = wrapReporterIfNecessary(theSuite, reporter) val testStartTime = System.currentTimeMillis (stopper, report, testStartTime) } def testMethodTakesAFixtureAndInformer(testName: String) = testName.endsWith(FixtureAndInformerInParens) def testMethodTakesAFixture(testName: String) = testName.endsWith(FixtureInParens) def simpleNameForTest(testName: String) = if (testName.endsWith(FixtureAndInformerInParens)) testName.substring(0, testName.length - FixtureAndInformerInParens.length) else if (testName.endsWith(FixtureInParens)) testName.substring(0, testName.length - FixtureInParens.length) else if (testName.endsWith(InformerInParens)) testName.substring(0, testName.length - InformerInParens.length) else testName // SKIP-SCALATESTJS,NATIVE-START def getMethodForTestName(theSuite: org.scalatest.Suite, testName: String): Method = { val candidateMethods = theSuite.getClass.getMethods.filter(_.getName == Suite.simpleNameForTest(testName)) val found = if (testMethodTakesAFixtureAndInformer(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 2 && paramTypes(1) == classOf[Informer] } ) else if (testMethodTakesAnInformer(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 1 && paramTypes(0) == classOf[Informer] } ) else if (testMethodTakesAFixture(testName)) candidateMethods.find( candidateMethod => { val paramTypes = candidateMethod.getParameterTypes paramTypes.length == 1 } ) else candidateMethods.find(_.getParameterTypes.length == 0) found match { case Some(method) => method case None => throw new IllegalArgumentException(Resources.testNotFound(testName)) } } // SKIP-SCALATESTJS,NATIVE-END // The substitution, if defined, indicates that the _1 string should be replace // by _2. This may transform "FunSpec" into "path.FunSpec", for example. def suiteToString(substitution: Option[(String, String)], theSuite: Suite): String = { val candidate = getSimpleNameOfAnObjectsClass(theSuite) val simpleName = substitution match { case Some((from, to)) if (candidate == from) => to case None => candidate } if (theSuite.nestedSuites.isEmpty) simpleName else simpleName + theSuite.nestedSuites.mkString("(", ", ", ")") } private[scalatest] def mergeMap[A, B](ms: List[Map[A, B]])(f: (B, B) => B): Map[A, B] = (Map[A, B]() /: (for (m <- ms; kv <- m) yield kv)) { (a, kv) => a + (if (a.contains(kv._1)) kv._1 -> f(a(kv._1), kv._2) else kv) } // SKIP-SCALATESTJS-START // Leave this around for a while so can print out a warning if we find testXXX methods. def yeOldeTestNames(theSuite: Suite): Set[String] = { def isTestMethod(m: Method) = { // Factored out to share code with FixtureSuite.testNames val (isInstanceMethod, simpleName, firstFour, paramTypes, hasNoParams, isTestNames, isTestTags, isTestDataFor) = isTestMethodGoodies(m) isInstanceMethod && (firstFour == "test") && !isTestDataFor && ((hasNoParams && !isTestNames && !isTestTags) || takesInformer(m)) } val testNameArray = for (m <- theSuite.getClass.getMethods; if isTestMethod(m)) yield if (takesInformer(m)) m.getName + InformerInParens else m.getName val result = TreeSet.empty[String](EncodedOrdering) ++ testNameArray if (result.size != testNameArray.length) { throw new NotAllowedException("Howdy", 0) } result } // SKIP-SCALATESTJS-END }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy