
org.scalatest.AsyncFunSuite.scala Maven / Gradle / Ivy
/*
* Copyright 2001-2014 Artima, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.scalatest
/**
* Enables testing of asynchronous code without blocking,
* using a style consistent with traditional FunSuite
tests.
*
*
* Given a Future
returned by the code you are testing,
* you need not block until the Future
completes before
* performing assertions against its value. You can instead map those
* assertions onto the Future
and return the resulting
* Future[Assertion]
to ScalaTest. The test will complete
* asynchronously, when the Future[Assertion]
completes.
*
* Here's an example AsyncFunSuite
:
*
*
* package org.scalatest.examples.asyncfunsuite
* import org.scalatest.AsyncFunSuite
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class AddSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* test("addSoon will eventually compute a sum of passed Ints") {
* val futureSum: Future[Int] = addSoon(1, 2)
* // You can map assertions onto a Future, then return
* // the resulting Future[Assertion] to ScalaTest:
* futureSum map { sum => assert(sum == 3) }
* }
*
* def addNow(addends: Int*): Int = addends.sum
*
* test("addNow will immediately compute a sum of passed Ints") {
* val sum: Int = addNow(1, 2)
* // You can also write synchronous tests, which
* // must result in type Assertion:
* assert(sum == 3)
* }
* }
*
*
*
* “test
” is a method, defined in AsyncFunSuite
, which will be invoked
* by the primary constructor of AddSuite
. You specify the name of the test as
* a string between the parentheses, and the test code itself between curly braces.
* The test code is a function passed as a by-name parameter to test
, which registers
* it for later execution. The result type of the by-name in an AsyncFunSuite
must
* be Future[Assertion]
.
*
*
*
* AsyncFunSuite
allows you to test asynchronous code without blocking. Instead of using
* scala.concurrent.Await
or org.scalatest.concurrent.ScalaFutures
to
* block until a Future
completes, then performing assertions on the result of the
* Future
, you map the assertions directly onto the Future
. ScalaTest
* assertions and matchers have result type Assertion
. Thus the result type of the
* first test in the example above is Future[Assertion]
. For clarity, here's the relevant code
* in a REPL session:
*
*
*
* scala> import org.scalatest._
* import org.scalatest._
*
* scala> import Assertions._
* import Assertions._
*
* scala> import scala.concurrent.Future
* import scala.concurrent.Future
*
* scala> import scala.concurrent.ExecutionContext
* import scala.concurrent.ExecutionContext
*
* scala> implicit val executionContext = ExecutionContext.Implicits.global
* executionContext: scala.concurrent.ExecutionContextExecutor = scala.concurrent.impl.ExecutionContextImpl@26141c5b
*
* scala> def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
* addSoon: (addends: Int*)scala.concurrent.Future[Int]
*
* scala> val futureSum: Future[Int] = addSoon(1, 2)
* futureSum: scala.concurrent.Future[Int] = scala.concurrent.impl.Promise$DefaultPromise@721f47b2
*
* scala> futureSum map { sum => assert(sum == 3) }
* res0: scala.concurrent.Future[org.scalatest.Assertion] = scala.concurrent.impl.Promise$DefaultPromise@3955cfcb
*
*
*
* The second test has result type Assertion
:
*
*
*
* scala> def addNow(addends: Int*): Int = addends.sum
* addNow: (addends: Int*)Int
*
* scala> val sum: Int = addNow(1, 2)
* sum: Int = 3
*
* scala> assert(sum == 3)
* res1: org.scalatest.Assertion = Succeeded
*
*
*
* The second test will be implicitly converted to Future[Assertion]
and registered.
* The implicit conversion is from Assertion
to Future[Assertion]
, so
* you must end synchronous tests in some ScalaTest assertion or matcher expression. If you need to,
* you can put succeed
at the end of the test body. succeed
is a field in
* trait Assertions
that returns the Succeeded
singleton:
*
*
*
* scala> import org.scalatest.Assertions._
* import org.scalatest.Assertions._
*
* scala> succeed
* res2: org.scalatest.Assertion = Succeeded
*
*
*
* Thus placing succeed
at the end of a test body will solve
* the type error:
*
*
*
* test("addNow will immediately compute a sum of passed Ints") {
* val sum: Int = addNow(1, 2)
* assert(sum == 3)
* println("hi") // println has result type Unit
* succeed // succeed has result type Assertion
* }
*
*
*
* An AsyncFunSuite
's lifecycle has two phases: the registration phase and the
* ready phase. It starts in registration phase and enters ready phase the first time
* run
is called on it. It then remains in ready phase for the remainder of its lifetime.
*
*
*
* Tests can only be registered with the test
method while the AsyncFunSuite
is
* in its registration phase. Any attempt to register a test after the AsyncFunSuite
has
* entered its ready phase, i.e., after run
has been invoked on the AsyncFunSuite
,
* will be met with a thrown TestRegistrationClosedException
. The recommended style
* of using AsyncFunSuite
is to register tests during object construction as is done in all
* the examples shown here. If you keep to the recommended style, you should never see a
* TestRegistrationClosedException
.
*
*
* The execution context and parallel execution
*
*
* In an AsyncFunSuite
you will need to define an implicit
* ExecutionContext
named executionContext
. This
* execution context will be used by AsyncFunSuite
to
* transform the Future[Assertion]
s returned by tests
* into the Future[Outcome]
returned by the test function
* passed to withAsyncFixture
.
* It is also intended to be used in the tests when an ExecutionContext
* is needed, including when you map assertions onto a future.
*
*
*
* By default, tests in an AsyncFunSuite
will be executed one after
* another, i.e., serially. This is true whether those tests are synchronous
* or asynchronous, no matter what threads are involved. This default behavior allows
* you to re-use a shared fixture, such as an external database that needs to be cleaned
* after each test, in multiple tests.
*
*
*
* If you want the tests of an AsyncFunSuite
to be executed in parallel, you
* must mix in ParallelTestExecution
.
* If ParallelTestExecution
is mixed in but no distributor is passed,
* tests will be started sequentially, by the single thread that invoked run
,
* without waiting for tests to complete before the next test is started. Nevertheless,
* asynchronous tests will be allowed to complete in parallel, using threads
* from the executionContext
. If ParallelTestExecution
is mixed
* in and a distributor is passed, tests will be started in parallel, using threads from
* the distributor and allowed to complete in parallel, using threads from the
* executionContext
.
*
*
* Ignored tests
*
*
* To support the common use case of temporarily disabling a test, with the
* good intention of resurrecting the test at a later time, AsyncFunSuite
provides registration
* methods that start with ignore
instead of test
. Here's an example:
*
*
*
* package org.scalatest.examples.asyncfunsuite.ignore
*
* import org.scalatest.AsyncFunSuite
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class AddSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* ignore("addSoon will eventually compute a sum of passed Ints") {
* val futureSum: Future[Int] = addSoon(1, 2)
* // You can map assertions onto a Future, then return
* // the resulting Future[Assertion] to ScalaTest:
* futureSum map { sum => assert(sum == 3) }
* }
*
* def addNow(addends: Int*): Int = addends.sum
*
* test("addNow will immediately compute a sum of passed Ints") {
* val sum: Int = addNow(1, 2)
* // You can also write synchronous tests. The body
* // must have result type Assertion:
* assert(sum == 3)
* }
* }
*
*
*
* If you run this version of AddSuite
with:
*
*
*
* scala> new AddSuite execute
*
*
*
* It will run only the second test and report that the first test was ignored:
*
*
*
* AddSuite:
* - addSoon will eventually compute a sum of passed Ints !!! IGNORED !!!
* - addNow will immediately compute a sum of passed Ints
*
*
*
* If you wish to temporarily ignore an entire suite of tests, you can (on the JVM, not Scala.js) annotate the test class with @Ignore
, like this:
*
*
*
* package org.scalatest.examples.asyncfunsuite.ignoreall
*
* import org.scalatest.AsyncFunSuite
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
* import org.scalatest.Ignore
*
* @Ignore
* class AddSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* test("addSoon will eventually compute a sum of passed Ints") {
* val futureSum: Future[Int] = addSoon(1, 2)
* // You can map assertions onto a Future, then return
* // the resulting Future[Assertion] to ScalaTest:
* futureSum map { sum => assert(sum == 3) }
* }
*
* def addNow(addends: Int*): Int = addends.sum
*
* test("addNow will immediately compute a sum of passed Ints") {
* val sum: Int = addNow(1, 2)
* // You can also write synchronous tests. The body
* // must have result type Assertion:
* assert(sum == 3)
* }
* }
*
*
*
* When you mark a test class with a tag annotation, ScalaTest will mark each test defined in that class with that tag.
* Thus, marking the AddSuite
in the above example with the @Ignore
tag annotation means that both tests
* in the class will be ignored. If you run the above AddSuite
in the Scala interpreter, you'll see:
*
*
*
* scala> new AddSuite execute
* AddSuite:
* - addSoon will eventually compute a sum of passed Ints !!! IGNORED !!!
* - addNow will immediately compute a sum of passed Ints !!! IGNORED !!!
*
*
*
* Note that marking a test class as ignored won't prevent it from being discovered by ScalaTest. Ignored classes
* will be discovered and run, and all their tests will be reported as ignored. This is intended to keep the ignored
* class visible, to encourage the developers to eventually fix and “un-ignore” it. If you want to
* prevent a class from being discovered at all (on the JVM, not Scala.js), use the DoNotDiscover
* annotation instead.
*
*
* Pending tests
*
*
* 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, 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, has not yet been implemented. Here's an example:
*
*
*
* package org.scalatest.examples.asyncfunsuite.pending
*
* import org.scalatest.AsyncFunSuite
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class AddSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* test("addSoon will eventually compute a sum of passed Ints") (pending)
*
* def addNow(addends: Int*): Int = addends.sum
*
* test("addNow will immediately compute a sum of passed Ints") {
* val sum: Int = addNow(1, 2)
* // You can also write synchronous tests. The body
* // must have result type Assertion:
* assert(sum == 3)
* }
* }
*
*
*
* (Note: "(pending)
" is the body of the test. Thus the test contains just one statement, an invocation
* of the pending
method, which throws TestPendingException
.)
* If you run this version of AddSuite
with:
*
*
*
* scala> new AddSuite execute
*
*
*
* It will run both tests, but report that first test is pending. You'll see:
*
*
*
* AddSuite:
* - addSoon will eventually compute a sum of passed Ints (pending)
* - addNow will immediately compute a sum of passed Ints
*
*
*
* One difference between an ignored test and a pending one is that an ignored test is intended to be used during a
* significant refactorings of the code under test, when tests break and you don't want to spend the time to fix
* all of them immediately. You can mark some of those broken tests as ignored temporarily, so that you can focus the red
* bar on just failing tests you actually want to fix immediately. Later you can go back and fix the ignored tests.
* In other words, by ignoring some failing tests temporarily, you can more easily notice failed tests that you actually
* want to fix. By contrast, a pending test is intended to be used before a test and/or the code under test is written.
* Pending indicates you've decided to write a test for a bit of behavior, but either you haven't written the test yet, or
* have only written part of it, or perhaps you've written the test but don't want to implement the behavior it tests
* until after you've implemented a different bit of behavior you realized you need first. Thus ignored tests are designed
* to facilitate refactoring of existing code whereas pending tests are designed to facilitate the creation of new code.
*
*
*
* One other difference between ignored and pending tests is that ignored tests are implemented as a test tag that is
* excluded by default. Thus an ignored test is never executed. By contrast, a pending test is implemented as a
* test that throws TestPendingException
(which is what calling the pending
method does). Thus
* the body of pending tests are executed up until they throw TestPendingException
.
*
*
* Tagging tests
*
*
* An AsyncFunSuite
's tests may be classified into groups by tagging them with string names.
* As with any suite, when executing an AsyncFunSuite
, groups of tests can
* optionally be included and/or excluded. To tag an AsyncFunSuite
's tests,
* you pass objects that extend class org.scalatest.Tag
to methods
* that register tests. Class Tag
takes one parameter, a string name. If you have
* created tag annotation interfaces as described in the Tag
documentation, then you
* will probably want to use tag names on your test functions that match. To do so, simply
* pass the fully qualified names of the tag interfaces to the Tag
constructor. For example, if you've
* defined a tag annotation interface with fully qualified name,
* com.mycompany.tags.DbTest
, then you could
* create a matching tag for AsyncFunSuite
s like this:
*
*
*
* package org.scalatest.examples.asyncfunsuite.tagging
*
* import org.scalatest.Tag
*
* object DbTest extends Tag("com.mycompany.tags.DbTest")
*
*
*
* Given these definitions, you could place AsyncFunSuite
tests into groups like this:
*
*
*
* import org.scalatest.AsyncFunSuite
* import org.scalatest.tagobjects.Slow
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class AddSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* test("addSoon will eventually compute a sum of passed Ints", Slow) {
* val futureSum: Future[Int] = addSoon(1, 2)
* // You can map assertions onto a Future, then return
* // the resulting Future[Assertion] to ScalaTest:
* futureSum map { sum => assert(sum == 3) }
* }
*
* def addNow(addends: Int*): Int = addends.sum
*
* test("addNow will immediately compute a sum of passed Ints",
* Slow, DbTest) {
*
* val sum: Int = addNow(1, 2)
* // You can also write synchronous tests. The body
* // must have result type Assertion:
* assert(sum == 3)
* }
* }
*
*
*
* This code marks both tests with the org.scalatest.tags.Slow
tag,
* and the second test with the com.mycompany.tags.DbTest
tag.
*
*
*
* The run
method takes a Filter
, whose constructor takes an optional
* Set[String]
called tagsToInclude
and a Set[String]
called
* tagsToExclude
. 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 tagsToExclude
,
* will be run.
*
*
*
* It is recommended, though not required, that you create a corresponding tag annotation when you
* create a Tag
object. A tag annotation allows you to tag all the tests of an AsyncFunSuite
in
* one stroke by annotating the class. For more information and examples, see the
* documentation for class Tag
.
*
*
*
* Shared fixtures
*
*
* A test fixture is composed of the objects and other artifacts (files, sockets, database
* connections, etc.) tests use to do their work.
* When multiple tests need to work with the same fixtures, it is important to try and avoid
* duplicating the fixture code across those tests. The more code duplication you have in your
* tests, the greater drag the tests will have on refactoring the actual production code.
*
*
*
* ScalaTest recommends three techniques to eliminate such code duplication:
*
*
*
* - Refactor using Scala
* - Override
withAsyncFixture
* - Mix in a before-and-after trait
*
*
* Each technique is geared towards helping you reduce code duplication without introducing
* instance var
s, shared mutable objects, or other dependencies between tests. Eliminating shared
* mutable state across tests will make your test code easier to reason about and more amenable for parallel
* test execution.
The following sections
* describe these techniques, including explaining the recommended usage
* for each. But first, here's a table summarizing the options:
*
*
*
*
*
* Refactor using Scala when different tests need different fixtures.
*
*
*
*
*
* get-fixture methods
*
*
* The extract method refactor helps you create a fresh instances of mutable fixture objects in each test
* that needs them, but doesn't help you clean them up when you're done.
*
*
*
*
*
* loan-fixture methods
*
*
* Factor out dupicate code with the loan pattern when different tests need different fixtures that must be cleaned up afterwards.
*
*
*
*
*
* Override withAsyncFixture
when most or all tests need the same fixture.
*
*
*
*
*
*
* withAsyncFixture(NoArgAsyncTest)
*
*
*
* The recommended default approach when most or all tests need the same fixture treatment. This general technique
* allows you, for example, to perform side effects at the beginning and end of all or most tests,
* transform the outcome of tests, retry tests, make decisions based on test names, tags, or other test data.
* Use this technique unless:
*
*
* - Different tests need different fixtures (refactor using Scala instead)
* - An exception in fixture code should abort the suite, not fail the test (use a before-and-after trait instead)
* - You have objects to pass into tests (override
withAsyncFixture(OneArgAsyncTest)
instead)
*
*
*
*
*
*
*
* withAsyncFixture(OneArgAsyncTest)
*
*
*
* Use when you want to pass the same fixture object or objects as a parameter into all or most tests.
*
*
*
*
*
* Mix in a before-and-after trait when you want an aborted suite, not a failed test, if the fixture code fails.
*
*
*
*
*
* BeforeAndAfter
*
*
* Use this boilerplate-buster when you need to perform the same side-effects before and/or after tests, rather than at the beginning or end of tests.
*
*
*
*
*
* BeforeAndAfterEach
*
*
* Use when you want to stack traits that perform the same side-effects before and/or after tests, rather than at the beginning or end of tests.
*
*
*
*
*
*
* Calling get-fixture methods
*
*
* If you need to create the same mutable fixture objects in multiple tests, and don't need to clean them up after using them, the simplest approach is to write one or
* more get-fixture methods. A get-fixture method returns a new instance of a needed fixture object (or an holder object containing
* multiple fixture objects) each time it is called. You can call a get-fixture method at the beginning of each
* test that needs the fixture, storing the returned object or objects in local variables. Here's an example:
*
*
*
* package org.scalatest.examples.asyncfunsuite.getfixture
*
* import org.scalatest.AsyncFunSuite
* import collection.mutable.ListBuffer
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class ExampleSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* class Fixture {
* val builder = new StringBuilder("ScalaTest is ")
* val buffer = new ListBuffer[String]
* }
*
* def fixture = new Fixture
*
* test("Testing should be easy") {
* val f = fixture
* f.builder.append("easy!")
* val fut = Future { (f.builder.toString, f.buffer.toList) }
* fut map { case (s, xs) =>
* assert(s === "ScalaTest is easy!")
* assert(xs.isEmpty)
* f.buffer += "sweet"
* succeed
* }
* }
*
* test("Testing should be fun") {
* val f = fixture
* f.builder.append("fun!")
* val fut = Future { (f.builder.toString, f.buffer.toList) }
* fut map { case (s, xs) =>
* assert(s === "ScalaTest is fun!")
* assert(xs.isEmpty)
* }
* }
* }
*
*
*
* The “f.
” in front of each use of a fixture object provides a visual indication of which objects
* are part of the fixture, but if you prefer, you can import the the members with “import f._
” and use the names directly.
*
*
*
* If you need to configure fixture objects differently in different tests, you can pass configuration into the get-fixture method. For example, if you could pass
* in an initial value for a mutable fixture object as a parameter to the get-fixture method.
*
*
*
* Overriding withAsyncFixture(NoArgAsyncTest)
*
*
* Although the get-fixture method approach takes care of setting up a fixture at the beginning of each
* test, it doesn't address the problem of cleaning up a fixture at the end of the test. If you just need to perform a side-effect at the beginning or end of
* a test, and don't need to actually pass any fixture objects into the test, you can override withAsyncFixture(NoArgAsyncTest)
, a
* method defined in trait AsyncSuite
, a supertrait of AsyncFunSuite
.
*
*
*
* Trait AsyncFunSuite
's runTest
method passes a no-arg async test function to
* withAsyncFixture(NoArgAsyncTest)
. It is withAsyncFixture
's
* responsibility to invoke that test function. The default implementation of withAsyncFixture
simply
* invokes the function and returns the result, like this:
*
*
*
* // Default implementation in trait AsyncSuite
* protected def withAsyncFixture(test: NoArgAsyncTest): Future[Outcome] = {
* test()
* }
*
*
*
* You can, therefore, override withAsyncFixture
to perform setup before invoking the test function,
* and/or perform cleanup after the test completes (by registering the cleanup code as a callback on the Future[Outcome]
* returned by the test function).
*
*
*
* The withAsyncFixture
method is designed to be stacked, and to enable this, you should always call the super
implementation
* of withAsyncFixture
, and let it invoke the test function rather than invoking the test function directly. In other words, instead of writing
* “test()
”, you should write “super.withAsyncFixture(test)
”, like this:
*
*
*
* // Your implementation
* override def withAsyncFixture(test: NoArgTest) = {
*
* // Perform setup
* val futureOutcome =
* super.withAsyncFixture(test) // Invoke the test function
*
* futureOutcome onComplete { _ =>
* // Perform cleanup
* }
*
* futureOutcome
* }
*
*
*
* Here's an example in which withAsyncFixture(NoArgAsyncTest)
is used to take a snapshot of the working directory if a test fails, and
* send that information to the standard output stream:
*
*
*
* package org.scalatest.examples.asyncfunsuite.noargtest
*
* import java.io.File
* import org.scalatest._
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class ExampleSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* override def withAsyncFixture(test: NoArgAsyncTest) = {
*
* val futureOutcome = super.withAsyncFixture(test)
*
* futureOutcome onSuccess {
* case failed: Failed =>
* val currDir = new File(".")
* val fileNames = currDir.list()
* println("Dir snapshot: " + fileNames.mkString(", "))
* failed
* case other => other
* }
*
* futureOutcome
* }
*
* def addSoon(addends: Int*): Future[Int] = Future { addends.sum }
*
* test("This test should succeed") {
* addSoon(1, 1) map { sum => assert(sum === 2) }
* }
*
* test("This test should fail") {
* addSoon(1, 1) map { sum => assert(sum === 3) }
* }
* }
*
*
*
* Running this version of ExampleSuite
in the interpreter in a directory with two files, hello.txt
and world.txt
* would give the following output:
*
*
*
* scala> new ExampleSuite execute
* ExampleSuite:
* - this test should succeed
* Dir snapshot: hello.txt, world.txt
* - this test should fail *** FAILED ***
* 2 did not equal 3 (:33)
*
*
*
* Note that the NoArgAsyncTest
passed to withAsyncFixture
, in addition to
* an apply
method that executes the test, also includes the test name and the config
* map passed to runTest
. Thus you can also use the test name and configuration objects in your withAsyncFixture
* implementation.
*
*
*
* Calling loan-fixture methods
*
*
* If you need to both pass a fixture object into a test and perform cleanup at the end of the test, you'll need to use the loan pattern.
* If different tests need different fixtures that require cleanup, you can implement the loan pattern directly by writing loan-fixture methods.
* A loan-fixture method takes a function whose body forms part or all of a test's code. It creates a fixture, passes it to the test code by invoking the
* function, then cleans up the fixture after the function returns.
*
*
*
* The following example shows three tests that use two fixtures, a database and a file. Both require cleanup after, so each is provided via a
* loan-fixture method. (In this example, the database is simulated with a StringBuffer
.)
*
*
*
* package org.scalatest.examples.asyncfunsuite.loanfixture
*
* import java.util.concurrent.ConcurrentHashMap
*
* object DbServer { // Simulating a database server
* type Db = StringBuffer
* private val databases = new ConcurrentHashMap[String, Db]
* def createDb(name: String): Db = {
* val db = new StringBuffer
* databases.put(name, db)
* db
* }
* def removeDb(name: String): Unit = {
* databases.remove(name)
* }
* }
*
* import org.scalatest._
* import DbServer._
* import java.util.UUID.randomUUID
* import java.io._
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class ExampleSuite extends AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* def withDatabase(testCode: Future[Db] => Future[Assertion]) = {
* val dbName = randomUUID.toString
* val futureDb = Future { createDb(dbName) } // create the fixture
* val futurePopulatedDb =
* futureDb map { db =>
* db.append("ScalaTest is ") // perform setup
* }
* val futureAssertion = testCode(futurePopulatedDb) // "loan" the fixture to the test
* futureAssertion onComplete { _ => removeDb(dbName) } // clean up the fixture
* futureAssertion
* }
*
* def withFile(testCode: (File, FileWriter) => Future[Assertion]) = {
* val file = File.createTempFile("hello", "world") // create the fixture
* val writer = new FileWriter(file)
* try {
* writer.write("ScalaTest is ") // set up the fixture
* val futureAssertion = testCode(file, writer) // "loan" the fixture to the test
* futureAssertion onComplete { _ => writer.close() } // clean up the fixture
* futureAssertion
* }
* catch {
* case ex: Throwable =>
* writer.close() // clean up the fixture
* throw ex
* }
* }
*
* // This test needs the file fixture
* test("Testing should be productive") {
* withFile { (file, writer) =>
* writer.write("productive!")
* writer.flush()
* assert(file.length === 24)
* }
* }
*
* // This test needs the database fixture
* test("Test code should be readable") {
* withDatabase { futureDb =>
* futureDb map { db =>
* db.append("readable!")
* assert(db.toString === "ScalaTest is readable!")
* }
* }
* }
*
* // This test needs both the file and the database
* test("Test code should be clear and concise") {
* withDatabase { futureDb =>
* withFile { (file, writer) => // loan-fixture methods compose
* futureDb map { db =>
* db.append("clear!")
* writer.write("concise!")
* writer.flush()
* assert(db.toString === "ScalaTest is clear!")
* assert(file.length === 21)
* }
* }
* }
* }
* }
*
*
*
* As demonstrated by the last test, loan-fixture methods compose. Not only do loan-fixture methods allow you to
* give each test the fixture it needs, they allow you to give a test multiple fixtures and clean everything up afterwards.
*
*
*
* Also demonstrated in this example is the technique of giving each test its own "fixture sandbox" to play in. When your fixtures
* involve external side-effects, like creating files or databases, it is a good idea to give each file or database a unique name as is
* done in this example. This keeps tests completely isolated, allowing you to run them in parallel if desired.
*
*
*
* Overriding withFixture(OneArgTest)
*
*
* If all or most tests need the same fixture, you can avoid some of the boilerplate of the loan-fixture method approach by using a fixture.AsyncSuite
* and overriding withAsyncFixture(OneArgAsyncTest)
.
* Each test in a fixture.AsyncSuite
takes a fixture as a parameter, allowing you to pass the fixture into
* the test. You must indicate the type of the fixture parameter by specifying FixtureParam
, and implement a
* withAsyncFixture
method that takes a OneArgAsyncTest
. This withAsyncFixture
method is responsible for
* invoking the one-arg async test function, so you can perform fixture set up before, invoking and passing
* the fixture into the test function, and perform clean up after the test completes (by registering the cleanup code as a
* callback on the Future[Outcome] returned by the test function).
*
*
*
* To enable the stacking of traits that define withAsyncFixture(NoArgAsyncTest)
, it is a good idea to let
* withAsyncFixture(NoArgAsyncTest)
invoke the test function instead of invoking the test
* function directly. To do so, you'll need to convert the OneArgAsyncTest
to a NoArgAsyncTest
. You can do that by passing
* the fixture object to the toNoArgAsyncTest
method of OneArgAsyncTest
. In other words, instead of
* writing “test(theFixture)
”, you'd delegate responsibility for
* invoking the test function to the withAsyncFixture(NoArgAsyncTest)
method of the same instance by writing:
*
*
*
* withAsyncFixture(test.toNoArgAsyncTest(theFixture))
*
*
*
* Here's a complete example:
*
*
*
* package org.scalatest.examples.asyncfunsuite.oneargasynctest
*
* import org.scalatest._
* import java.io._
* import scala.concurrent.Future
* import scala.concurrent.ExecutionContext
*
* class ExampleSuite extends fixture.AsyncFunSuite {
*
* implicit val executionContext = ExecutionContext.Implicits.global
*
* case class FixtureParam(file: File, writer: FileWriter)
*
* def withAsyncFixture(test: OneArgAsyncTest): Future[Outcome] = {
*
* // create the fixture
* val file = File.createTempFile("hello", "world")
* val writer = new FileWriter(file)
* val theFixture = FixtureParam(file, writer)
*
* try {
* writer.write("ScalaTest is ") // set up the fixture
* // "loan" the fixture to the test
* withAsyncFixture(test.toNoArgAsyncTest(theFixture))
* }
* catch {
* case ex: Throwable =>
* writer.close() // clean up the fixture
* throw ex
* }
* }
*
* test("Testing should be easy") { f =>
* val futureFile =
* Future {
* f.writer.write("easy!")
* f.writer.flush()
* f.file
* }
* futureFile map { file => assert(file.length === 18) }
* }
*
* test("Testing should be fun") { f =>
* val futureFile =
* Future {
* f.writer.write("fun!")
* f.writer.flush()
* f.file
* }
* futureFile map { file => assert(file.length === 17) }
* }
* }
*
*
*
* In this example, the tests actually required two fixture objects, a File
and a FileWriter
. In such situations you can
* simply define the FixtureParam
type to be a tuple containing the objects, or as is done in this example, a case class containing
* the objects. For more information on the withAsyncFixture(OneArgAsyncTest)
technique, see the documentation for fixture.AsyncFunSuite
.
*
*
*/
abstract class AsyncFunSuite extends AsyncFunSuiteLike {
/**
* Returns a user friendly string for this suite, composed of the
* simple name of the class (possibly simplified further by removing dollar signs if added by the Scala interpeter) and, if this suite
* contains nested suites, the result of invoking toString
on each
* of the nested suites, separated by commas and surrounded by parentheses.
*
* @return a user-friendly string for this suite
*/
override def toString: String = Suite.suiteToString(None, this)
}