package concurrent
ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.
- Source
- package.scala
- Alphabetic
- By Inheritance
- concurrent
- AnyRef
- Any
- Hide All
- Show All
- Public
- All
Type Members
- trait AbstractPatienceConfiguration extends ScaledTimeSpans
Trait that defines an abstract
patienceConfig
method that is implemented inPatienceConfiguration
and can be overriden in stackable modification traits such asIntegrationPatience
.Trait that defines an abstract
patienceConfig
method that is implemented inPatienceConfiguration
and can be overriden in stackable modification traits such asIntegrationPatience
.The main purpose of
AbstractPatienceConfiguration
is to differentiate corePatienceConfiguration
traits, such asEventually
andWaiters
, from stackable modification traits forPatienceConfiguration
s such asIntegrationPatience
. Because these stackable traits extendAbstractPatienceConfiguration
instead ofSuite
, you can't simply mix in a stackable trait:class ExampleSpec extends FunSpec with IntegrationPatience // Won't compile
The previous code is undesirable because
IntegrationPatience
would have no affect on the class. Instead, you need to mix in a corePatienceConfiguration
trait and mix the stackableIntegrationPatience
trait into that, like this:class ExampleSpec extends FunSpec with Eventually with IntegrationPatience // Compiles fine
The previous code is better because
IntegrationPatience
does have an effect: it modifies the behavior ofEventually
. - trait AsyncCancelAfterFailure extends AsyncTestSuiteMixin
Trait that when mixed into a
AsyncTestSuite
cancels any remaining tests in thatAsyncTestSuite
instance after a test fails.Trait that when mixed into a
AsyncTestSuite
cancels any remaining tests in thatAsyncTestSuite
instance after a test fails.The intended use case for this trait is if you have a suite of long-running tests that are related such that if one fails, you aren't interested in running the others, you can use this trait to simply cancel any remaining tests, so you need not wait long for them to complete.
- trait AsyncTimeLimitedTests extends AsyncTestSuiteMixin with TimeLimits
Trait that when mixed into an asynchronous suite class establishes a time limit for its tests.
Trait that when mixed into an asynchronous suite class establishes a time limit for its tests.
This trait overrides
withFixture
, wrapping asuper.withFixture(test)
call in afailAfter
invocation, specifying a timeout obtained by invokingtimeLimit
:failAfter(timeLimit) { super.withFixture(test) }
Note that the
failAfter
method executes the body of the by-name passed to it using the same thread that invokedfailAfter
. This means that the calling ofwithFixture
method will be run using the same thread, but the test body may be run using a different thread, depending on theexecutionContext
set at theAsyncTestSuite
level.The
timeLimit
field is abstract in this trait. Thus you must specify a time limit when you use it. For example, the following code specifies that each test must complete within 200 milliseconds:import org.scalatest.AsyncFunSpec import org.scalatest.concurrent.AsyncTimeLimitedTests import org.scalatest.time.SpanSugar._ class ExampleSpec extends AsyncFunSpec with AsyncTimeLimitedTests { // Note: You may need to either write 200.millis or (200 millis), or // place a semicolon or blank line after plain old 200 millis, to // avoid the semicolon inference problems of postfix operator notation. val timeLimit = 200 millis describe("An asynchronous time-limited test") { it("should succeed if it completes within the time limit") { Thread.sleep(100) succeed } it("should fail if it is taking too darn long") { Thread.sleep(300) succeed } } }
If you run the above
ExampleSpec
, the second test will fail with the error message:The test did not complete within the specified 200 millisecond time limit.
Different from
TimeLimitedTests
,AsyncTimeLimitedTests
does not supportInterruptor
for now. - trait Futures extends PatienceConfiguration
Trait that facilitates testing with futures.
Trait that facilitates testing with futures.
This trait defines a
FutureConcept
trait that can be used to implicitly wrap different kinds of futures, thereby providing a uniform testing API for futures. The three ways this trait enables you to test futures are:1. Invoking
isReadyWithin
, to assert that a future is ready within a a specified time period. Here's an example:assert(result.isReadyWithin(100 millis))
2. Invoking
futureValue
, to obtain a futures result within a specified or implicit time period, like this:assert(result.futureValue === 7) // Or, if you expect the future to fail: assert(result.failed.futureValue.isInstanceOf[ArithmeticException])
3. Passing the future to
whenReady
, and performing assertions on the result value passed to the given function, as in:whenReady(result) { s => s should be ("hello") }
The
whenReady
construct periodically inspects the passed future, until it is either ready or the configured timeout has been surpassed. If the future becomes ready before the timeout,whenReady
passes the future's value to the specified function.To make
whenReady
more broadly applicable, the type of future it accepts is aFutureConcept[T]
, whereT
is the type of value promised by the future. Passing a future towhenReady
requires an implicit conversion from the type of future you wish to pass (the modeled type) toFutureConcept[T]
. SubtraitJavaFutures
provides an implicit conversion fromjava.util.concurrent.Future[T]
toFutureConcept[T]
.For example, the following invocation of
whenReady
would succeed (not throw an exception):import org.scalatest._ import Matchers._ import concurrent.Futures._ import java.util.concurrent._ val exec = Executors.newSingleThreadExecutor val task = new Callable[String] { def call() = { Thread.sleep(50); "hi" } } whenReady(exec.submit(task)) { s => s should be ("hi") }
However, because the default timeout is 150 milliseconds, the following invocation of
whenReady
would ultimately produce aTestFailedException
:val task = new Callable[String] { def call() = { Thread.sleep(500); "hi" } } whenReady(exec.submit(task)) { s => s should be ("hi") }
Assuming the default configuration parameters, a
timeout
of 150 milliseconds and aninterval
of 15 milliseconds, were passed implicitly towhenReady
, the detail message of the thrownTestFailedException
would look like:The future passed to whenReady was never ready, so whenReady timed out. Queried 95 times, sleeping 10 milliseconds between each query.
Configuration of
whenReady
The
whenReady
methods of this trait can be flexibly configured. The two configuration parameters forwhenReady
along with their default values and meanings are described in the following table:Configuration Parameter Default Value Meaning timeout scaled(150 milliseconds) the maximum amount of time to allow unsuccessful queries before giving up and throwing TestFailedException
interval scaled(15 milliseconds) the amount of time to sleep between each query The default values of both timeout and interval are passed to the
scaled
method, inherited fromScaledTimeSpans
, so that the defaults can be scaled up or down together with other scaled time spans. See the documentation for traitScaledTimeSpans
for more information.The
whenReady
methods of traitFutures
each take aPatienceConfig
object as an implicit parameter. This object provides values for the two configuration parameters. TraitFutures
provides an implicitval
nameddefaultPatience
with each configuration parameter set to its default value. If you want to set one or more configuration parameters to a different value for all invocations ofwhenReady
in a suite you can override this val (or hide it, for example, if you are importing the members of theFutures
companion object rather than mixing in the trait). For example, if you always want the defaulttimeout
to be 2 seconds and the defaultinterval
to be 5 milliseconds, you can overridedefaultPatience
, like this:implicit override val defaultPatience = PatienceConfig(timeout = Span(2, Seconds), interval = Span(5, Millis))
Or, hide it by declaring a variable of the same name in whatever scope you want the changed values to be in effect:
implicit val defaultPatience = PatienceConfig(timeout = Span(2, Seconds), interval = Span(5, Millis))
In addition to taking a
PatienceConfig
object as an implicit parameter, thewhenReady
methods of traitFutures
include overloaded forms that take one or twoPatienceConfigParam
objects that you can use to override the values provided by the implicitPatienceConfig
for a singlewhenReady
invocation. For example, if you want to settimeout
to 6 seconds for just one particularwhenReady
invocation, you can do so like this:whenReady (exec.submit(task), timeout(Span(6, Seconds))) { s => s should be ("hi") }
This invocation of
eventually
will use 6000 fortimeout
and whatever value is specified by the implicitly passedPatienceConfig
object for theinterval
configuration parameter. If you want to set both configuration parameters in this way, just list them separated by commas:whenReady (exec.submit(task), timeout(Span(6, Seconds)), interval(Span(500, Millis))) { s => s should be ("hi") }
You can also import or mix in the members of
SpanSugar
if you want a more concise DSL for expressing time spans:whenReady (exec.submit(task), timeout(6 seconds), interval(500 millis)) { s => s should be ("hi") }
Note: The
whenReady
construct was in part inspired by thewhenDelivered
matcher of the BlueEyes project, a lightweight, asynchronous web framework for Scala. - trait IntegrationPatience extends AbstractPatienceConfiguration
Stackable modification trait for
PatienceConfiguration
that provides default timeout and interval values appropriate for integration testing.Stackable modification trait for
PatienceConfiguration
that provides default timeout and interval values appropriate for integration testing.The default values for the parameters are:
Configuration Parameter Default Value timeout
scaled(15 seconds)
interval
scaled(150 milliseconds)
The default values of both timeout and interval are passed to the
scaled
method, inherited fromScaledTimeSpans
, so that the defaults can be scaled up or down together with other scaled time spans. See the documentation for traitScaledTimeSpans
for more information.Mix this trait into any class that uses
PatienceConfiguration
(such as classes that mix inEventually
orWaiters
) to get timeouts tuned towards integration testing, like this:class ExampleSpec extends FeatureSpec with Eventually with IntegrationPatience { // ... }
- trait PatienceConfiguration extends AbstractPatienceConfiguration
Trait providing methods and classes used to configure timeouts and, where relevant, the interval between retries.
Trait providing methods and classes used to configure timeouts and, where relevant, the interval between retries.
This trait is called
PatienceConfiguration
because it allows configuration of two values related to patience: The timeout specifies how much time asynchronous operations will be given to succeed before giving up. The interval specifies how much time to wait between checks to determine success when polling.The default values for timeout and interval provided by trait
PatienceConfiguration
are tuned for unit testing, where running tests as fast as possible is a high priority and subsystems requiring asynchronous operations are therefore often replaced by mocks. This table shows the default values:Configuration Parameter Default Value timeout
scaled(150 milliseconds)
interval
scaled(15 milliseconds)
Values more appropriate to integration testing, where asynchronous operations tend to take longer because the tests are run against the actual subsytems (not mocks), can be obtained by mixing in trait
IntegrationPatience
.The default values of both timeout and interval are passed to the
scaled
method, inherited fromScaledTimeSpans
, so that the defaults can be scaled up or down together with other scaled time spans. See the documentation for traitScaledTimeSpans
for more information.Timeouts are used by the
eventually
methods of traitEventually
and theawait
method of classWaiter
, a member of traitWaiters
. Intervals are used by theeventually
methods. - trait ScalaFutures extends Futures
Provides an implicit conversion from
scala.concurrent.Future[T]
toFutureConcept[T]
.Provides an implicit conversion from
scala.concurrent.Future[T]
toFutureConcept[T]
.This trait enables you to invoke the methods defined on
FutureConcept
on a ScalaFuture
, as well as to pass a Scala future to thewhenReady
methods of supertraitFutures
. The three ways this trait enables you to test futures are:1. Invoking
isReadyWithin
, to assert that a future is ready within a a specified time period. Here's an example:assert(result.isReadyWithin(100 millis))
2. Invoking
futureValue
, to obtain a futures result within a specified or implicit time period, like this:assert(result.futureValue === 7) // Or, if you expect the future to fail: assert(result.failed.futureValue.isInstanceOf[ArithmeticException])
3. Passing the future to
whenReady
, and performing assertions on the result value passed to the given function, as in:whenReady(result) { s => s should be ("hello") }
The
whenReady
construct periodically inspects the passed future, until it is either ready or the configured timeout has been surpassed. If the future becomes ready before the timeout,whenReady
passes the future's value to the specified function.To make
whenReady
more broadly applicable, the type of future it accepts is aFutureConcept[T]
, whereT
is the type of value promised by the future. Passing a future towhenReady
requires an implicit conversion from the type of future you wish to pass (the modeled type) toFutureConcept[T]
. SubtraitJavaFutures
provides an implicit conversion fromjava.util.concurrent.Future[T]
toFutureConcept[T]
.For example, the following invocation of
whenReady
would succeed (not throw an exception):import org.scalatest._ import Matchers._ import concurrent.Futures._ import java.util.concurrent._ val exec = Executors.newSingleThreadExecutor val task = new Callable[String] { def call() = { Thread.sleep(50); "hi" } } whenReady(exec.submit(task)) { s => s should be ("hi") }
However, because the default timeout is 150 milliseconds, the following invocation of
whenReady
would ultimately produce aTestFailedException
:val task = new Callable[String] { def call() = { Thread.sleep(500); "hi" } } whenReady(exec.submit(task)) { s => s should be ("hi") }
Assuming the default configuration parameters, a
timeout
of 150 milliseconds and aninterval
of 15 milliseconds, were passed implicitly towhenReady
, the detail message of the thrownTestFailedException
would look like:The future passed to whenReady was never ready, so whenReady timed out. Queried 95 times, sleeping 10 milliseconds between each query.
Configuration of
whenReady
The
whenReady
methods of this trait can be flexibly configured. The two configuration parameters forwhenReady
along with their default values and meanings are described in the following table:Configuration Parameter Default Value Meaning timeout scaled(150 milliseconds) the maximum amount of time to allow unsuccessful queries before giving up and throwing TestFailedException
interval scaled(15 milliseconds) the amount of time to sleep between each query The default values of both timeout and interval are passed to the
scaled
method, inherited fromScaledTimeSpans
, so that the defaults can be scaled up or down together with other scaled time spans. See the documentation for traitScaledTimeSpans
for more information.The
whenReady
methods of traitFutures
each take aPatienceConfig
object as an implicit parameter. This object provides values for the two configuration parameters. TraitFutures
provides an implicitval
nameddefaultPatience
with each configuration parameter set to its default value. If you want to set one or more configuration parameters to a different value for all invocations ofwhenReady
in a suite you can override this val (or hide it, for example, if you are importing the members of theFutures
companion object rather than mixing in the trait). For example, if you always want the defaulttimeout
to be 2 seconds and the defaultinterval
to be 5 milliseconds, you can overridedefaultPatience
, like this:implicit override val defaultPatience = PatienceConfig(timeout = Span(2, Seconds), interval = Span(5, Millis))
Or, hide it by declaring a variable of the same name in whatever scope you want the changed values to be in effect:
implicit val defaultPatience = PatienceConfig(timeout = Span(2, Seconds), interval = Span(5, Millis))
In addition to taking a
PatienceConfig
object as an implicit parameter, thewhenReady
methods of traitFutures
include overloaded forms that take one or twoPatienceConfigParam
objects that you can use to override the values provided by the implicitPatienceConfig
for a singlewhenReady
invocation. For example, if you want to settimeout
to 6 seconds for just one particularwhenReady
invocation, you can do so like this:whenReady (exec.submit(task), timeout(Span(6, Seconds))) { s => s should be ("hi") }
This invocation of
eventually
will use 6000 fortimeout
and whatever value is specified by the implicitly passedPatienceConfig
object for theinterval
configuration parameter. If you want to set both configuration parameters in this way, just list them separated by commas:whenReady (exec.submit(task), timeout(Span(6, Seconds)), interval(Span(500, Millis))) { s => s should be ("hi") }
You can also import or mix in the members of
SpanSugar
if you want a more concise DSL for expressing time spans:whenReady (exec.submit(task), timeout(6 seconds), interval(500 millis)) { s => s should be ("hi") }
Note: The
whenReady
construct was in part inspired by thewhenDelivered
matcher of the BlueEyes project, a lightweight, asynchronous web framework for Scala. - trait ScaledTimeSpans extends AnyRef
Trait providing a
scaled
method that can be used to scale timeSpan
s used during the testing of asynchronous operations.Trait providing a
scaled
method that can be used to scale timeSpan
s used during the testing of asynchronous operations.The
scaled
method allows tests of asynchronous operations to be tuned according to need. For example,Span
s can be scaled larger when running tests on slower continuous integration servers or smaller when running on faster development machines.The
Double
factor by which to scale theSpan
s passed toscaled
is obtained from thespanScaleFactor
method, also declared in this trait. By default this method returns 1.0, but can be configured to return a different value by passing a-F
argument toRunner
(or an equivalent mechanism in an ant, sbt, or Maven build file).The default timeouts and intervals defined for traits
Eventually
andWaiters
invokescaled
, so those defaults will be scaled automatically. Other than such defaults, however, to get aSpan
to scale you'll need to explicitly pass it toscaled
. For example, here's how you would scale aSpan
you supply to thefailAfter
method from traitTimeouts
:failAfter(scaled(150 millis)) { // ... }
The reason
Span
s are not scaled automatically in the general case is to make code obvious. If a reader seesfailAfter(1 second)
, it will mean exactly that: fail after one second. And if aSpan
will be scaled, the reader will clearly see that as well:failAfter(scaled(1 second))
.Overriding
spanScaleFactor
You can override the
spanScaleFactor
method to configure the factor by a different means. For example, to configure the factor from Akka TestKit's test time factor you might create a trait like this:import org.scalatest.concurrent.ScaledTimeSpans import akka.actor.ActorSystem import akka.testkit.TestKitExtension trait AkkaSpanScaleFactor extends ScaledTimeSpans { override def spanScaleFactor: Double = TestKitExtension.get(ActorSystem()).TestTimeFactor }
This trait overrides
spanScaleFactor
so that it takes its scale factor from Akka'sapplication.conf
file. You could then scaleSpan
s tenfold in Akka's configuration file like this:akka { test { timefactor = 10.0 } }
Armed with this trait and configuration file, you can simply mix trait
AkkaSpanScaleFactor
into any test class whoseSpan
s you want to scale, like this:class MySpec extends FunSpec with Eventually with AkkaSpanScaleFactor { // .. }
- class SelectorSignaler extends Signaler
Strategy for signaling an operation in which
wakeup
is called on thejava.nio.channels.Selector
passed to the constructor.Strategy for signaling an operation in which
wakeup
is called on thejava.nio.channels.Selector
passed to the constructor.This class can be used for configuration when using traits
TimeLimits
andTimeLimitedTests
. - trait Signaler extends AnyRef
Strategy for signaling an operation after a timeout expires.
Strategy for signaling an operation after a timeout expires.
An instance of this trait is used for configuration when using traits
TimeLimits
andTimeLimitedTests
. - class SocketSignaler extends Signaler
Strategy for signaling an operation in which
close
is called on thejava.net.Socket
passed to the constructor.Strategy for signaling an operation in which
close
is called on thejava.net.Socket
passed to the constructor.This class can be used for configuration when using traits
TimeLimits
andTimeLimitedTests
. - trait TimeLimitedTests extends TestSuiteMixin
Trait that when mixed into a suite class establishes a time limit for its tests.
Trait that when mixed into a suite class establishes a time limit for its tests.
Unfortunately this trait experienced a potentially breaking change in 3.0: previously this trait declared a
defaultTestInterruptor
val
of typeInterruptor
, in 3.0 that was renamed todefaultTestSignaler
and given typeSignaler
. The reason is that the defaultInterruptor
,ThreadInterruptor
, did not make sense on Scala.js—in fact, the entire notion of interruption did not make sense on Scala.js.Signaler
's default isDoNotSignal
, which is a better default on Scala.js, and works fine as a default on the JVM.Timeouts
was left the same in 3.0, so existing code using it would continue to work as before, but after a deprecation periodTimeouts
will be supplanted byTimeLimits
, which usesSignaler
.TimeLimitedTests
now usesTimeLimits
instead ofTimeouts
, so if you overrode the defaultInterruptor
before, you'll need to change it to the equivalentSignaler
. And if you were depending on the default being aThreadInterruptor
, you'll need to overridedefaultTestSignaler
and set it toThreadSignaler
.This trait overrides
withFixture
, wrapping asuper.withFixture(test)
call in afailAfter
invocation, specifying a time limit obtained by invokingtimeLimit
and aSignaler
by invokingdefaultTestSignaler
:failAfter(timeLimit) { super.withFixture(test) } (defaultTestSignaler)
Note that the
failAfter
method executes the body of the by-name passed to it using the same thread that invokedfailAfter
. This means that the same thread will run thewithFixture
method as well as each test, so no extra synchronization is required. A second thread is used to run a timer, and if the timeout expires, that second thread will attempt to signal the main test thread via thedefaultTestSignaler
.The
timeLimit
field is abstract in this trait. Thus you must specify a time limit when you use it. For example, the following code specifies that each test must complete within 200 milliseconds:import org.scalatest.FunSpec import org.scalatest.concurrent.TimeLimitedTests import org.scalatest.time.SpanSugar._ class ExampleSpec extends FunSpec with TimeLimitedTests { // Note: You may need to either write 200.millis or (200 millis), or // place a semicolon or blank line after plain old 200 millis, to // avoid the semicolon inference problems of postfix operator notation. val timeLimit = 200 millis describe("A time-limited test") { it("should succeed if it completes within the time limit") { Thread.sleep(100) } it("should fail if it is taking too darn long") { Thread.sleep(300) } } }
If you run the above
ExampleSpec
, the second test will fail with the error message:The test did not complete within the specified 200 millisecond time limit.
The
failAfter
method uses anSignaler
to attempt to signal the main test thread if the timeout expires. The defaultSignaler
returned by thedefaultTestSignaler
method is aDoNotSignal
, which does not signal the main test thread to stop. If you wish to change this signaling strategy, overridedefaultTestSignaler
to return a differentSignaler
. For example, here's how you'd change the default toThreadSignaler
, which will interrupt the main test thread when time is up:import org.scalatest.FunSpec import org.scalatest.concurrent.{ThreadSignaler, TimeLimitedTests} import org.scalatest.time.SpanSugar._ class ExampleSignalerSpec extends FunSpec with TimeLimitedTests { val timeLimit = 200 millis override val defaultTestSignaler = ThreadSignaler describe("A time-limited test") { it("should succeed if it completes within the time limit") { Thread.sleep(100) } it("should fail if it is taking too darn long") { Thread.sleep(300) } } }
Like the previous incarnation of
ExampleSuite
, the second test will fail with an error message that indicates a timeout expired. But whereas in the previous case, theThread.sleep
would be interrupted after 200 milliseconds, in this case it is never interrupted. In the previous case, the failed test requires a little over 200 milliseconds to run. In this case, because thesleep(300)
is never interrupted, the failed test requires a little over 300 milliseconds to run. - trait TimeLimits extends AnyRef
Trait that provides
failAfter
andcancelAfter
methods, which allow you to specify a time limit for an operation passed as a by-name parameter, as well as a way to signal it if the operation exceeds its time limit.Trait that provides
failAfter
andcancelAfter
methods, which allow you to specify a time limit for an operation passed as a by-name parameter, as well as a way to signal it if the operation exceeds its time limit.The time limit is passed as the first parameter, as a
Span
. The operation is passed as the second parameter. ASignaler
, a strategy for interrupting the operation, is passed as an implicit third parameter. Here's a simple example of its use:failAfter(Span(100, Millis)) { Thread.sleep(200) }
The above code will eventually produce a
TestFailedDueToTimeoutException
with a message that indicates a time limit has been exceeded:The code passed to failAfter did not complete within 100 milliseconds.
If you use
cancelAfter
in place offailAfter
, aTestCanceledException
will be thrown instead, also with a message that indicates a time limit has been exceeded:The code passed to cancelAfter did not complete within 100 milliseconds.
If you prefer you can mix in or import the members of
SpanSugar
and place a units value after the integer timeout. Here are some examples:import org.scalatest.time.SpanSugar._ failAfter(100 millis) { Thread.sleep(200) } failAfter(1 second) { Thread.sleep(2000) }
The code passed via the by-name parameter to
failAfter
orcancelAfter
will be executed by the thread that invokedfailAfter
orcancelAfter
, so that no synchronization is necessary to access variables declared outside the by-name.var result = -1 // No need to make this volatile failAfter(100 millis) { result = accessNetService() } result should be (99)
The
failAfter
orcancelAfter
method will create a timer that runs on a different thread than the thread that invokedfailAfter
orcancelAfter
, so that it can detect when the time limit has been exceeded and attempt to signal the main thread. Because different operations can require different signaling strategies, thefailAfter
andcancelAfter
methods accept an implicit third parameter of typeSignaler
that is responsible for signaling the main thread.Configuring
failAfter
orcancelAfter
with aSignaler
The
Signaler
companion object declares an implicitval
of typeSignaler
that returns aDoNotSignal
. This serves as the default signaling strategy. If you wish to use a different strategy, you can declare an implicitval
that establishes a differentSignaler
as the policy. Here's an example in which the default signaling strategy is changed toThreadSignaler
, which does not attempt to interrupt the main thread in any way:override val signaler: Signaler = ThreadSignaler failAfter(100 millis) { Thread.sleep(500) }
As with the default
Signaler
, the above code will eventually produce aTestFailedDueToTimeoutException
with a message that indicates a timeout expired. However, instead of throwing the exception after approximately 500 milliseconds, it will throw it after approximately 100 milliseconds.This illustrates an important feature of
failAfter
andcancelAfter
: it will throw aTestFailedDueToTimeoutException
(orTestCanceledException
in case ofcancelAfter
) if the code passed as the by-name parameter takes longer than the specified timeout to execute, even if it is allowed to run to completion beyond the specified timeout and returns normally.ScalaTest provides the following
Signaler
implementations:Signaler
implementationUsage DoNotSignal The default signaler, does not attempt to interrupt the main test thread in any way ThreadSignaler Invokes interrupt
on the main test thread. This will set the interrupted status for the main test thread and, if the main thread is blocked, will in some cases cause the main thread to complete abruptly with anInterruptedException
.SelectorSignaler Invokes wakeup
on the passedjava.nio.channels.Selector
, which will cause the main thread, if blocked inSelector.select
, to complete abruptly with aClosedSelectorException
.SocketSignaler Invokes close
on thejava.io.Socket
, which will cause the main thread, if blocked in a read or write of anjava.io.InputStream
orjava.io.OutputStream
that uses theSocket
, to complete abruptly with aSocketException
.You may wish to create your own
Signaler
in some situations. For example, if your operation is performing a loop and can check a volatile flag each pass through the loop, you could write aSignaler
that sets that flag so that the next time around, the loop would exit.
Value Members
- object DoNotSignal extends Signaler
Signaling strategy in which nothing is done to try and signal or interrupt an operation.
Signaling strategy in which nothing is done to try and signal or interrupt an operation.
This object can be used for configuration when using traits
TimeLimits
andTimeLimitedTests
. - object PatienceConfiguration
- object ScalaFutures extends ScalaFutures
Companion object that facilitates the importing of
ScalaFutures
members as an alternative to mixing in the trait.Companion object that facilitates the importing of
ScalaFutures
members as an alternative to mixing in the trait. One use case is to importScalaFutures
's members so you can use them in the Scala interpreter. - object SelectorSignaler
Companion object that provides a factory method for a
SelectorSignaler
. - object Signaler
Companion object that provides a factory method for a
Singlaer
defined in terms of a function from a function of typeThread
to Unit. - object SocketSignaler
Companion object that provides a factory method for a
SocketSignaler
. - object TestExecutionContext
- object ThreadSignaler extends Signaler
Strategy for signaling an operation in which
interrupt
is called on theThread
passed toapply
.Strategy for signaling an operation in which
interrupt
is called on theThread
passed toapply
.This object can be used for configuration when using traits
TimeLimits
andTimeLimitedTests
. - object TimeLimits extends TimeLimits
Companion object that facilitates the importing of
Timeouts
members as an alternative to mixing in the trait.Companion object that facilitates the importing of
Timeouts
members as an alternative to mixing in the trait. One use case is to importTimeouts
's members so you can use them in the Scala interpreter.