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

org.scalatest.Suite.scala Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2001-2013 Artima, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.scalatest

import java.lang.annotation._
import java.io.Serializable
import java.lang.reflect.Constructor
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.nio.charset.CoderMalfunctionError
import javax.xml.parsers.FactoryConfigurationError
import javax.xml.transform.TransformerFactoryConfigurationError
import Suite.simpleNameForTest
import Suite.parseSimpleName
import Suite.stripDollars
import Suite.formatterForSuiteStarting
import Suite.formatterForSuiteCompleted
import Suite.checkForPublicNoArgConstructor
import Suite.checkChosenStyles
import Suite.formatterForSuiteAborted
import Suite.anExceptionThatShouldCauseAnAbort
import Suite.getSimpleNameOfAnObjectsClass
import Suite.takesInformer
import Suite.handleFailedTest
import Suite.isTestMethodGoodies
import Suite.testMethodTakesAnInformer
import scala.collection.immutable.TreeSet
import Suite.getIndentedTextForTest
import Suite.getEscapedIndentedTextForTest
import Suite.getTopOfClass
import Suite.getTopOfMethod
import Suite.getTopOfMethod
import Suite.getSuiteRunTestGoodies
import Suite.autoTagClassAnnotations
import org.scalatest.events._
import org.scalatest.tools.StandardOutReporter
import Suite.getMessageForException
import Suite.reportTestStarting
import Suite.reportTestIgnored
import Suite.reportTestSucceeded
import Suite.reportTestPending
import Suite.reportTestCanceled
import Suite.reportInfoProvided
import Suite.createInfoProvided
import Suite.createMarkupProvided
import Suite.wrapReporterIfNecessary
import Suite.getMethodForTestName
import scala.reflect.NameTransformer
import tools.SuiteDiscoveryHelper
import tools.Runner
import exceptions.StackDepthExceptionHelper.getStackDepthFun
import exceptions._
import exceptions._
import collection.mutable.ListBuffer
import collection.GenTraversable
import annotation.tailrec
import collection.immutable
import OutcomeOf.outcomeOf

/*
 * 

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> new SetSuite execute
 * 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 ShouldMatchers, you can * write suites that look like: *

* *
 * package org.scalatest.examples.suite.matchers
 *
 * import org.scalatest._
 *
 * class SetSuite extends Suite with ShouldMatchers {
 *
 *   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` {
 *     evaluating { Set.empty.head } should produce [NoSuchElementException]
 *   }
 * }
 * 
* *

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

* *

* Prior to ScalaTest 2.0.M4, trait Suite served two purposes: 1) It served as the base * class of ScalaTest's family of style traits, and 2) It was itself a style trait in which tests are methods. * Although it will continue to serve its first purpose, it has been deprecated as a style trait. Pre-existing code * that used Suite as a style trait to define tests as methods will continue to work during the * deprecation period, but will generate a deprecation warning. Please change all such uses of Suite * to use trait Spec instead. *

* *

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> new ASCIISuite execute
 * 
* *

* 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 fixture.Suite * 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. *

* * *

Treatment of java.lang.Errors

* *

* 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 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 */ @Finders(Array("org.scalatest.finders.MethodFinder")) trait Suite extends Assertions with AbstractSuite with Serializable { thisSuite => import Suite.TestMethodPrefix, Suite.InformerInParens, Suite.IgnoreAnnotation /** * A test function taking no arguments and returning an Outcome. * *

* For more detail and examples, see the relevant section in the * documentation for trait fixture.FlatSpec. *

*/ protected trait NoArgTest extends (() => Outcome) with TestData { /** * Runs the body of the test, returning an Outcome. */ def apply(): Outcome } // Keep this out of the public until there's a use case demonstrating its need private[scalatest] object NoArgTest { def apply(test: NoArgTest)(f: => Outcome): NoArgTest = { new NoArgTest { def apply(): Outcome = { f } val text: String = test.text val configMap: ConfigMap = test.configMap val scopes: collection.immutable.IndexedSeq[String] = test.scopes val name: String = test.name val tags: Set[String] = test.tags } } } /** * 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 /** * 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 NullPointerException 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 ) { if (configMap == null) throw new NullPointerException("configMap was null") 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))) 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 runStartTime = System.currentTimeMillis if (stats) dispatch(RunStarting(tracker.nextOrdinal(), expectedTestCount(filter), configMap)) val suiteStartTime = System.currentTimeMillis def dispatchSuiteAborted(e: Throwable) { 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(thisSuite.getClass.getName), Some(e), Some(duration), formatter, Some(SeeStackDepthException))) } try { val formatter = formatterForSuiteStarting(thisSuite) dispatch(SuiteStarting(tracker.nextOrdinal(), thisSuite.suiteName, thisSuite.suiteId, Some(thisSuite.getClass.getName), formatter, Some(getTopOfClass(thisSuite)))) run( None, Args(dispatch, Stopper.default, filter, configMap, None, tracker, Set.empty) ) val suiteCompletedFormatter = formatterForSuiteCompleted(thisSuite) val duration = System.currentTimeMillis - suiteStartTime dispatch(SuiteCompleted(tracker.nextOrdinal(), thisSuite.suiteName, thisSuite.suiteId, Some(thisSuite.getClass.getName), 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))) } finally { dispatch.dispatchDisposeAndWaitUntilDone() } } /** * Executes this Suite, printing results to the standard output. * *

* This method, which simply invokes the other overloaded form of execute with default parameter values, * is intended for use only as a mini-DSL for the Scala interpreter. It allows you to execute a Suite in the * interpreter with a minimum of finger typing: *

* *
   * scala> new SetSpec execute
   * An empty Set
   * - should have size 0
   * - should produce NoSuchElementException when head is invoked !!! IGNORED !!!
   * 
* *

* If you do ever want to invoke execute outside the Scala interpreter, it is best style to invoke it with * empty parens to indicate it has a side effect, like this: *

* *
   * // Use empty parens form in regular code (outside the Scala interpreter)
   * (new ExampleSuite).execute()
   * 
*/ final def execute { execute() } /** * 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]] = { val testNameSet = testNames val testTags = Map() ++ (for (testName <- testNameSet; if !getTags(testName).isEmpty) yield testName -> (Set() ++ getTags(testName))) autoTagClassAnnotations(testTags, this) } private def getTags(testName: String) = for { a <- getMethodForTestName(thisSuite, testName).getDeclaredAnnotations annotationClass = a.annotationType if annotationClass.isAnnotationPresent(classOf[TagAnnotation]) } yield annotationClass.getName /** * A Set of test names. If this Suite contains no tests, this method returns an empty Set. * *

* Suite has been deprecated as a style trait. During the deprecation period, the following behavior will continue * to work as before, but will go away at the conclusion of the deprecation period: * This trait's implementation of this method uses Java reflection to discover all public methods whose name starts with "test", * which take either nothing or a single Informer as parameters. For each discovered test method, it assigns a test name * comprised of just the method name if the method takes no parameters, or the method name plus (Informer) if the * method takes a Informer. Here are a few method signatures and the names that this trait's implementation assigns them: *

* *
   * def testCat() {}         // test name: "testCat"
   * def testCat(Informer) {} // test name: "testCat(Informer)"
   * def testDog() {}         // test name: "testDog"
   * def testDog(Informer) {} // test name: "testDog(Informer)"
   * def test() {}            // test name: "test"
   * def test(Informer) {}    // test name: "test(Informer)"
   * 
* *

* This trait's implementation of this method returns an immutable Set of all such names, excluding the name * testNames. The iterator obtained by invoking elements on this * returned Set will produce the test names in their natural order, as determined by String's * compareTo method. *

* *

* This trait's implementation of runTests invokes this method * and calls runTest for each test name in the order they appear in the returned Set's iterator. * Although this trait's implementation of this method returns a Set whose iterator produces String * test names in a well-defined order, the contract of this method does not required a defined order. Subclasses are free to * override this method and return test names in an undefined order, or in a defined order that's different from String's * natural order. *

* *

* Subclasses may override this method to produce test names in a custom manner. One potential reason to override testNames is * to run tests in a different order, for example, to ensure that tests that depend on other tests are run after those other tests. * Another potential reason to override is allow tests to be defined in a different manner, such as methods annotated @Test annotations * (as is done in JUnitSuite and TestNGSuite) or test functions registered during construction (as is * done in FunSuite and FunSpec). *

* *

* In ScalaTest's event model, a test may be surrounded by “scopes.” Each test and scope is associated with string of text. * A test's name is concatenation of the text of any surrounding scopes followed by the text provided with the test * itself, after each text element has been trimmed and one space inserted between each component. Here's an example: *

* *
   * package org.scalatest.examples.freespec
   *
   * import org.scalatest.FreeSpec
   *
   * class SetSpec extends FreeSpec {
   *
   *   "A Set" - {
   *     "when empty" - {
   *       "should have size 0" in {
   *         assert(Set.empty.size === 0)
   *       }
   *
   *       "should produce NoSuchElementException when head is invoked" in {
   *         intercept[NoSuchElementException] {
   *           Set.empty.head
   *         }
   *       }
   *     }
   *   }
   * }
   * 
* *

* The above FreeSpec contains two tests, both nested inside the same two scopes. The outermost scope names * the subject, A Set. The nested scope qualifies the subject with when empty. Inside that * scope are the two tests. The text of the tests are: *

* *

    *
  • should have size 0
  • *
  • should produce NoSuchElementException when head is invoked
  • *
* *

* Therefore, the names of these two tests are: *

* *
    *
  • A Stack when empty should have size 0
  • *
  • A Stack when empty should produce NoSuchElementException when head is invoked
  • *
* *

* Note that because the component scope and test text strings are trimmed, any leading or trailing space will be dropped * before they are strung together to form the test name, with each trimmed component separated by a space. If the scopes * in the above example had text " A Set " and " when empty ", and the first test had text * " should have size 0 ", its test name would still be the same, "A Set when empty should have size 0". *

*/ def testNames: Set[String] = { def isTestMethod(m: Method) = { // Factored out to share code with fixture.Suite.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 <- 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 } /* 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 the passed test function in the context of a fixture established by this method. * *

* This method should set up the fixture needed by the tests of the * current suite, invoke the test function, and if needed, perform any clean * up needed after the test completes. Because the NoArgTest function * passed to this method takes no parameters, preparing the fixture will require * side effects, such as reassigning instance vars in this Suite or initializing * a globally accessible external database. If you want to avoid reassigning instance vars * you can use fixture.Suite. *

* *

* This trait's implementation of runTest invokes this method for each test, passing * in a NoArgTest whose apply method will execute the code of the test. *

* *

* This trait's implementation of this method simply invokes the passed NoArgTest function. *

* * @param test the no-arg test function to run with a fixture */ protected def withFixture(test: NoArgTest): Outcome = { test() } /** * Run a test. * *

* This trait's implementation uses Java reflection to invoke on this object the test method identified by the passed testName. *

* *

* Implementations of this method are responsible for ensuring a TestStarting event * is fired to the Reporter before executing any test, and either TestSucceeded, * TestFailed, TestPending or TestCanceled after executing any nested * Suite. (If a test is marked with the org.scalatest.Ignore tag, the * runTests method is responsible for ensuring a TestIgnored event is fired and that * this runTest method is not invoked for that ignored test.) *

* * @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 NullPointerException 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 = { if (testName == null) throw new NullPointerException("testName was null") if (args == null) throw new NullPointerException("args was null") import args._ val (stopRequested, report, method, testStartTime) = getSuiteRunTestGoodies(thisSuite, stopper, reporter, testName) reportTestStarting(this, report, tracker, testName, testName, rerunner, Some(getTopOfMethod(thisSuite, testName))) val formatter = getEscapedIndentedTextForTest(testName, 1, true) val messageRecorderForThisTest = new MessageRecorder(report) val informerForThisTest = MessageRecordingInformer( messageRecorderForThisTest, (message, payload, isConstructingThread, testWasPending, testWasCanceled, location) => createInfoProvided(thisSuite, report, tracker, Some(testName), message, payload, 2, location, isConstructingThread, true) ) // TODO: Was using reportInfoProvided here before, to double check with Bill for changing to markup provided. val documenterForThisTest = MessageRecordingDocumenter( messageRecorderForThisTest, (message, _, isConstructingThread, testWasPending, testWasCanceled, location) => createMarkupProvided(thisSuite, report, tracker, Some(testName), message, 2, location, isConstructingThread) // TODO: Need a test that fails because testWasCanceleed isn't being passed ) val argsArray: Array[Object] = if (testMethodTakesAnInformer(testName)) { Array(informerForThisTest) } else Array() try { val theConfigMap = configMap val testData = testDataFor(testName, theConfigMap) withFixture( new NoArgTest { val name = testData.name def apply(): Outcome = { outcomeOf { method.invoke(thisSuite, argsArray: _*) } } val configMap = testData.configMap val scopes = testData.scopes val text = testData.text val tags = testData.tags } ).toUnit val duration = System.currentTimeMillis - testStartTime reportTestSucceeded(this, report, tracker, testName, testName, messageRecorderForThisTest.recordedEvents(false, false), duration, formatter, rerunner, Some(getTopOfMethod(thisSuite, method))) SucceededStatus } catch { case ite: InvocationTargetException => val t = ite.getTargetException t match { case _: TestPendingException => val duration = System.currentTimeMillis - testStartTime // testWasPending = true so info's printed out in the finally clause show up yellow reportTestPending(this, report, tracker, testName, testName, messageRecorderForThisTest.recordedEvents(true, false), duration, formatter, Some(getTopOfMethod(thisSuite, method))) SucceededStatus case e: TestCanceledException => val duration = System.currentTimeMillis - testStartTime val message = getMessageForException(e) val formatter = getEscapedIndentedTextForTest(testName, 1, true) // testWasCanceled = true so info's printed out in the finally clause show up yellow reportTestCanceled(this, report, t, testName, testName, messageRecorderForThisTest.recordedEvents(false, true), rerunner, tracker, duration, formatter, Some(TopOfMethod(thisSuite.getClass.getName, method.toGenericString()))) SucceededStatus case e if !anExceptionThatShouldCauseAnAbort(e) => val duration = System.currentTimeMillis - testStartTime handleFailedTest(thisSuite, t, testName, messageRecorderForThisTest.recordedEvents(false, false), report, tracker, getEscapedIndentedTextForTest(testName, 1, true), duration) FailedStatus case e => throw e } case e if !anExceptionThatShouldCauseAnAbort(e) => val duration = System.currentTimeMillis - testStartTime handleFailedTest(thisSuite, e, testName, messageRecorderForThisTest.recordedEvents(false, false), report, tracker, getEscapedIndentedTextForTest(testName, 1, true), duration) FailedStatus case e: Throwable => throw e } } /** * 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 NullPointerException 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 = { if (testName == null) throw new NullPointerException("testName was null") if (args == null) throw new NullPointerException("args was null") if (!this.isInstanceOf[Spec] && !this.isInstanceOf[Suites] && !this.isInstanceOf[Specs] && !this.isInstanceOf[Sequential] && !this.isInstanceOf[Stepwise]) println("Unfortunately Suite has been deprecated as a style trait. Please use trait Spec instead.") import args._ val theTestNames = testNames if (theTestNames.size > 0) checkChosenStyles(configMap, styleName) val stopRequested = stopper // 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 (!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 NullPointerException 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 = { if (testName == null) throw new NullPointerException("testName was null") if (args == null) throw new NullPointerException("args was null") import args._ val originalThreadName = Thread.currentThread.getName try { Thread.currentThread.setName(SuiteHelpers.augmentedThreadName(originalThreadName, suiteName)) val stopRequested = stopper 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 (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 NullPointerException if any passed parameter is null. */ protected def runNestedSuites(args: Args): Status = { if (args == null) throw new NullPointerException("args was null") import args._ val stopRequested = stopper val report = wrapReporterIfNecessary(thisSuite, reporter) def callExecuteOnSuite(nestedSuite: Suite): Status = { if (!stopRequested()) { // Create a Rerunner if the Suite has a no-arg constructor val hasPublicNoArgConstructor = Suite.checkForPublicNoArgConstructor(nestedSuite.getClass) val rawString = Resources("suiteExecutionStarting") val formatter = formatterForSuiteStarting(nestedSuite) val suiteStartTime = System.currentTimeMillis report(SuiteStarting(tracker.nextOrdinal(), nestedSuite.suiteName, nestedSuite.suiteId, Some(nestedSuite.getClass.getName), formatter, Some(TopOfClass(nestedSuite.getClass.getName)), 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, stopRequested, filter, configMap, distributor, tracker, Set.empty)) val rawString = Resources("suiteCompletedNormally") val formatter = formatterForSuiteCompleted(nestedSuite) val duration = System.currentTimeMillis - suiteStartTime report(SuiteCompleted(tracker.nextOrdinal(), nestedSuite.suiteName, nestedSuite.suiteId, Some(nestedSuite.getClass.getName), Some(duration), formatter, Some(TopOfClass(nestedSuite.getClass.getName)), 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(nestedSuite.getClass.getName), Some(e), Some(duration), formatter, Some(SeeStackDepthException), nestedSuite.rerunner)) FailedStatus } } } else FailedStatus } val statusBuffer = new ListBuffer[Status]() if (!filter.excludeNestedSuites) { val nestedSuitesArray = nestedSuites.toArray distributor match { case None => for (nestedSuite <- nestedSuitesArray) { if (!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 // XXX /** * Throws TestPendingException to indicate a test is pending. * *

* A pending test is one that has been given a name but is not yet implemented. The purpose of * pending tests is to facilitate a style of testing in which documentation of behavior is sketched * out before tests are written to verify that behavior (and often, the before the behavior of * the system being tested is itself implemented). Such sketches form a kind of specification of * what tests and functionality to implement later. *

* *

* To support this style of testing, a test can be given a name that specifies one * bit of behavior required by the system being tested. The test can also include some code that * sends more information about the behavior to the reporter when the tests run. At the end of the test, * it can call method pending, which will cause it to complete abruptly with TestPendingException. * Because tests in ScalaTest can be designated as pending with TestPendingException, both the test name and any information * sent to the reporter when running the test can appear in the report of a test run. (In other words, * the code of a pending test is executed just like any other test.) However, because the test completes abruptly * with TestPendingException, the test will be reported as pending, to indicate * the actual test, and possibly the functionality it is intended to test, has not yet been implemented. *

* *

* Note: This method always completes abruptly with a TestPendingException. Thus it always has a side * effect. Methods with side effects are usually invoked with parentheses, as in pending(). This * method is defined as a parameterless method, in flagrant contradiction to recommended Scala style, because it * forms a kind of DSL for pending tests. It enables tests in suites such as FunSuite or FunSpec * to be denoted by placing "(pending)" after the test name, as in: *

* *
   * test("that style rules are not laws") (pending)
   * 
* *

* Readers of the code see "pending" in parentheses, which looks like a little note attached to the test name to indicate * it is pending. Whereas "(pending()) looks more like a method call, "(pending)" lets readers * stay at a higher level, forgetting how it is implemented and just focusing on the intent of the programmer who wrote the code. *

*/ def pending: PendingNothing = { throw new TestPendingException } /** * Execute the passed block of code, and if it completes abruptly, throw TestPendingException, else * throw TestFailedException. * *

* This method can be used to temporarily change a failing test into a pending test in such a way that it will * automatically turn back into a failing test once the problem originally causing the test to fail has been fixed. * At that point, you need only remove the pendingUntilFixed call. In other words, a * pendingUntilFixed surrounding a block of code that isn't broken is treated as a test failure. * The motivation for this behavior is to encourage people to remove pendingUntilFixed calls when * there are no longer needed. *

* *

* This method facilitates a style of testing in which tests are written before the code they test. Sometimes you may * encounter a test failure that requires more functionality than you want to tackle without writing more tests. In this * case you can mark the bit of test code causing the failure with pendingUntilFixed. You can then write more * tests and functionality that eventually will get your production code to a point where the original test won't fail anymore. * At this point the code block marked with pendingUntilFixed will no longer throw an exception (because the * problem has been fixed). This will in turn cause pendingUntilFixed to throw TestFailedException * with a detail message explaining you need to go back and remove the pendingUntilFixed call as the problem orginally * causing your test code to fail has been fixed. *

* * @param f a block of code, which if it completes abruptly, should trigger a TestPendingException * @throws TestPendingException if the passed block of code completes abruptly with an Exception or AssertionError */ def pendingUntilFixed(f: => Unit) { val isPending = try { f false } catch { case _: Exception => true case _: AssertionError => true } if (isPending) throw new TestPendingException else throw new TestFailedException(Resources("pendingUntilFixed"), 2) } /** * 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 val isAccessible = SuiteDiscoveryHelper.isAccessibleSuite(suiteClass) val hasWrapWithAnnotation = suiteClass.getAnnotation(classOf[WrapWith]) != null if (isAccessible || hasWrapWithAnnotation) Some(suiteClass.getName) else None } /** * Suite style name. */ 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 = { val suiteTags = for { a <- this.getClass.getDeclaredAnnotations annotationClass = a.annotationType if annotationClass.isAnnotationPresent(classOf[TagAnnotation]) } yield annotationClass.getName val testTags: Set[String] = try { getTags(testName).toSet } catch { case e: IllegalArgumentException => Set.empty[String] } new TestData { val configMap = theConfigMap val name = testName val scopes = Vector.empty val text = testName val tags = Set.empty ++ suiteTags ++ testTags } } } private[scalatest] object Suite { val TestMethodPrefix = "test" val InformerInParens = "(Informer)" val IgnoreAnnotation = "org.scalatest.Ignore" def getSimpleNameOfAnObjectsClass(o: AnyRef) = stripDollars(parseSimpleName(o.getClass.getName)) // [bv: this is a good example of the expression type refactor. I moved this from SuiteClassNameListCellRenderer] // this will be needed by the GUI classes, etc. def parseSimpleName(fullyQualifiedName: String) = { val dotPos = fullyQualifiedName.lastIndexOf('.') // [bv: need to check the dotPos != fullyQualifiedName.length] if (dotPos != -1 && dotPos != fullyQualifiedName.length) fullyQualifiedName.substring(dotPos + 1) else fullyQualifiedName } def checkForPublicNoArgConstructor(clazz: java.lang.Class[_]) = { try { val constructor = clazz.getConstructor(new Array[java.lang.Class[T] forSome { type T }](0): _*) Modifier.isPublic(constructor.getModifiers) } catch { case nsme: NoSuchMethodException => false } } // This attempts to strip dollar signs that happen when using the interpreter. It is quite fragile // and already broke once. In the early days, all funky dollar sign encrusted names coming out of // the interpreter started with "line". Now they don't, but in both cases they seemed to have at // least one "$iw$" in them. So now I leave the string alone unless I see a "$iw$" in it. Worst case // is sometimes people will get ugly strings coming out of the interpreter. -bv April 3, 2012 def stripDollars(s: String): String = { val lastDollarIndex = s.lastIndexOf('$') if (lastDollarIndex < s.length - 1) if (lastDollarIndex == -1 || !s.contains("$iw$")) s else s.substring(lastDollarIndex + 1) else { // The last char is a dollar sign val lastNonDollarChar = s.reverse.find(_ != '$') lastNonDollarChar match { case None => s case Some(c) => { val lastNonDollarIndex = s.lastIndexOf(c) if (lastNonDollarIndex == -1) s else stripDollars(s.substring(0, lastNonDollarIndex + 1)) } } } } def diffStrings(s: String, t: String): Tuple2[String, String] = { def findCommonPrefixLength(s: String, t: String): Int = { val max = s.length.min(t.length) // the maximum potential size of the prefix var i = 0 var found = false while (i < max & !found) { found = (s.charAt(i) != t.charAt(i)) if (!found) i = i + 1 } i } def findCommonSuffixLength(s: String, t: String): Int = { val max = s.length.min(t.length) // the maximum potential size of the suffix var i = 0 var found = false while (i < max & !found) { found = (s.charAt(s.length - 1 - i) != t.charAt(t.length - 1 - i)) if (!found) i = i + 1 } i } if (s != t) { val commonPrefixLength = findCommonPrefixLength(s, t) val commonSuffixLength = findCommonSuffixLength(s.substring(commonPrefixLength), t.substring(commonPrefixLength)) val prefix = s.substring(0, commonPrefixLength) val suffix = if (s.length - commonSuffixLength < 0) "" else s.substring(s.length - commonSuffixLength) val sMiddleEnd = s.length - commonSuffixLength val tMiddleEnd = t.length - commonSuffixLength val sMiddle = s.substring(commonPrefixLength, sMiddleEnd) val tMiddle = t.substring(commonPrefixLength, tMiddleEnd) val MaxContext = 20 val shortPrefix = if (commonPrefixLength > MaxContext) "..." + prefix.substring(prefix.length - MaxContext) else prefix val shortSuffix = if (commonSuffixLength > MaxContext) suffix.substring(0, MaxContext) + "..." else suffix (shortPrefix + "[" + sMiddle + "]" + shortSuffix, shortPrefix + "[" + tMiddle + "]" + shortSuffix) } else (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) = a match { case aStr: String => { b match { case bStr: String => { Suite.diffStrings(aStr, bStr) } case _ => (a, b) } } case _ => (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.size == 0) && (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] = Some(IndentedText(message, message, 0)) /* def simpleNameForTest(testName: String) = if (testName.endsWith(InformerInParens)) testName.substring(0, testName.length - InformerInParens.length) else testName */ def anExceptionThatShouldCauseAnAbort(throwable: Throwable): Boolean = throwable match { case _: AnnotationFormatError | /* _: org.scalatest.TestRegistrationClosedException | _: org.scalatest.DuplicateTestNameException | _: 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 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 Spec 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) = { 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(" ", " ") def unparsedXml(value: String) = scala.xml.Unparsed(value) def xmlContent(value: String) = unparsedXml(substituteHtmlSpace(value)) 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]) { 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, 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]) { 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]) { 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]) { 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]) { 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]) { 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 ) { 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 ) { 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 ) { 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 ) { 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] ) { 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] ) { 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] ) { 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, stackTrace.getFileName)) else None } else None } def checkChosenStyles(configMap: ConfigMap, styleName: String) { val chosenStyleSet = if (configMap.isDefinedAt(Runner.CHOSEN_STYLES)) configMap(Runner.CHOSEN_STYLES).asInstanceOf[Set[String]] else Set.empty[String] if (chosenStyleSet.size > 0 && !chosenStyleSet.contains(styleName)) { val e = if (chosenStyleSet.size == 1) new NotAllowedException(Resources("notTheChosenStyle", styleName, chosenStyleSet.head), getStackDepthFun("Suite.scala", "checkChosenStyles")) else new NotAllowedException(Resources("notOneOfTheChosenStyles", styleName, Suite.makeListForHumans(Vector.empty ++ chosenStyleSet.iterator)), getStackDepthFun("Scala.scala", "checkChosenStyles")) throw e } } // If it contains a space, or is an empty string, put quotes around it. OTherwise people might // get confused by the chosenStyles error message. def makeListForHumans(words: Vector[String]): String = { val quotedWords = words map { w => if (w.length == 0 || w.indexOf(' ') >= 0) "\"" + w + "\"" else w } quotedWords.length match { case 0 => "" //case 1 if quotedWords(0).isEmpty => "\"\"" case 1 => quotedWords(0) case 2 => Resources("leftAndRight", quotedWords(0), quotedWords(1)) case _ => val (leading, trailing) = quotedWords.splitAt(quotedWords.length - 2) leading.mkString(", ") + ", " + Resources("leftCommaAndRight", trailing(0), trailing(1)) } } def autoTagClassAnnotations(tags: Map[String, Set[String]], theSuite: Suite) = { val suiteTags = for { a <- theSuite.getClass.getDeclaredAnnotations 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]] Runner.mergeMap[String, Set[String]](List(tags, autoTestTags)) ( _ ++ _ ) } def handleFailedTest( theSuite: Suite, throwable: Throwable, testName: String, recordedEvents: collection.immutable.IndexedSeq[RecordableEvent], report: Reporter, tracker: Tracker, formatter: Formatter, duration: Long ) { 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, Some(throwable), Some(duration), Some(formatter), Some(SeeStackDepthException), theSuite.rerunner, payload)) } def getTopOfClass(theSuite: Suite) = TopOfClass(theSuite.getClass.getName) def getTopOfMethod(theSuite: Suite, method: Method) = TopOfMethod(theSuite.getClass.getName, method.toGenericString()) def getTopOfMethod(theSuite: Suite, testName: String) = TopOfMethod(theSuite.getClass.getName, getMethodForTestName(theSuite, testName).toGenericString()) // Factored out to share this with fixture.Suite.runTest def getSuiteRunTestGoodies(theSuite: Suite, stopper: Stopper, reporter: Reporter, testName: String): (Stopper, Reporter, Method, Long) = { val (stopRequested, report, testStartTime) = getRunTestGoodies(theSuite, stopper, reporter, testName) val method = getMethodForTestName(theSuite, testName) (stopRequested, report, method, testStartTime) } // Sharing this with FunSuite and fixture.FunSuite as well as Suite and fixture.Suite def getRunTestGoodies(theSuite: Suite, stopper: Stopper, reporter: Reporter, testName: String): (Stopper, Reporter, Long) = { val stopRequested = stopper val report = wrapReporterIfNecessary(theSuite, reporter) val testStartTime = System.currentTimeMillis (stopRequested, report, testStartTime) } // Wrap any non-DispatchReporter, non-CatchReporter in a CatchReporter, // so that exceptions are caught and transformed // into error messages on the standard error stream. def wrapReporterIfNecessary(theSuite: Suite, reporter: Reporter): Reporter = reporter match { case cr: CatchReporter => cr case _ => theSuite.createCatchReporter(reporter) } val FixtureAndInformerInParens = "(FixtureParam, Informer)" val FixtureInParens = "(FixtureParam)" 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 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)) } } // 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("(", ", ", ")") } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy