Skip to main content
Version: 2.x

TestClock

In most cases we want unit tests to be as fast as possible. Waiting for real time to pass by is a real killer for this.

ZIO exposes a TestClock that can control the time. We can deterministically and efficiently test effects involving the passage of time without actually having to wait for the full amount of time to pass.

Calls to sleep and methods derived from it will semantically block until the clock time is set/adjusted to on or after the time the effect is scheduled to run.

Instead of waiting for actual time to pass, sleep and methods implemented in terms of it schedule effects to take place at a given clock time. Users can adjust the clock time using the adjust and setTime methods, and all effects scheduled to take place on or before that time will automatically be run in order.

For example, here is how we can test ZIO#timeout using TestClock:

import zio._
import zio.test._

for {
fiber <- ZIO.sleep(5.minutes).timeout(1.minute).fork
_ <- TestClock.adjust(1.minute)
result <- fiber.join
} yield assertTrue(result.isEmpty)

Note how we forked the fiber that sleep was invoked on. Calls to sleep and methods derived from it will semantically block until the time is set to on or after the time they are scheduled to run.

If we didn't fork the fiber on which we called sleep we would never get to set the time on the line below. Thus, a useful pattern when using TestClock is to fork the effect being tested, then adjust the clock time, and finally verify that the expected effects have been performed.

Clock time is just like a clock on the wall, except that in our TestClock, the clock is broken. Instead of moving by itself, the clock time only changes when adjusted or set by the user, using the adjust and setTime methods. The clock time never changes by itself.

When the clock is adjusted, any effects scheduled to run on or before the new clock time will automatically be run, in order.

For example, here is how we can test an effect that recurs with a fixed delay:

import zio._
import zio.Queue
import zio.test._

for {
q <- Queue.unbounded[Unit]
_ <- q.offer(()).delay(60.minutes).forever.fork
a <- q.poll.map(_.isEmpty)
_ <- TestClock.adjust(60.minutes)
b <- q.take.as(true)
c <- q.poll.map(_.isEmpty)
_ <- TestClock.adjust(60.minutes)
d <- q.take.as(true)
e <- q.poll.map(_.isEmpty)
} yield assertTrue(a && b && c && d && e)

Here we verify that no effect is performed before the recurrence period, that an effect is performed after the recurrence period, and that the effect is performed exactly once.

The key thing to note here is that after each recurrence the next recurrence is scheduled to occur at the appropriate time in the future, so when we adjust the clock by 60 minutes exactly one value is placed in the queue, and when we adjust the clock by another 60 minutes exactly one more value is placed in the queue.

Controlling the Clockโ€‹

TestClock has the following operations to control and inspect the clock:

OperationDescription
adjust(duration)Moves the clock forward by duration and runs the sleeps that end on or before the new time, in order.
adjustWith(duration)(zio)Runs zio and, in parallel, adjusts the clock by duration. Returns the result of zio.
setTime(instant)Sets the clock to instant and runs the sleeps that end on or before it, in order.
setTimeZone(zone)Sets the time zone that Clock.currentDateTime and Clock.localDateTime use. The clock time does not change.
timeZoneReturns the current time zone.
sleepsReturns the end times of the sleeps that have not been resumed yet.
saveReturns an effect that restores the clock time, the time zone and the pending sleeps to their values at the save.

Setting the Timeโ€‹

TestClock.setTime moves the clock to a given Instant, instead of by a duration. All sleeps that end on or before that instant are resumed, in order of their end times:

import zio._
import zio.test._
import java.time.Instant

for {
fiber <- ZIO.sleep(1.hour).as("done").fork
_ <- TestClock.setTime(Instant.parse("1970-01-01T01:00:00Z"))
result <- fiber.join
now <- Clock.instant
} yield assertTrue(
result == "done",
now == Instant.parse("1970-01-01T01:00:00Z")
)

The clock can move back as well. A negative duration given to adjust moves the clock back, and an instant given to setTime that is earlier than the current time does the same. In both cases no sleeping fiber is resumed, because the new time is before the end time of every pending sleep.

A call to ZIO.sleep with a zero or negative duration returns at once and never waits for the clock, while a call with Duration.Infinity never returns.

Running an Effect While Adjusting the Clockโ€‹

TestClock.adjustWith runs an effect and adjusts the clock in parallel, so we do not have to fork the effect ourselves. The following test is equivalent to forking the sleep, adjusting the clock and joining the fiber:

import zio._
import zio.test._

for {
result <- TestClock.adjustWith(1.minute)(ZIO.sleep(30.seconds).as("slept"))
} yield assertTrue(result == "slept")

Inspecting the Pending Sleepsโ€‹

TestClock.sleeps returns the end times of the sleeps that have not been resumed yet. The sleeps scheduled since the last adjust or setTime come first, most recently scheduled first. Each adjust and setTime sorts the remaining sleeps by end time.

A sleep whose fiber was interrupted stays in the list until the clock reaches its end time:

import zio._
import zio.test._

for {
fiber1 <- ZIO.sleep(10.seconds).fork
fiber2 <- ZIO.sleep(5.seconds).fork
_ <- TestClock.adjust(1.second)
before <- TestClock.sleeps
_ <- fiber1.interrupt
after <- TestClock.sleeps
_ <- TestClock.adjust(9.seconds)
done <- TestClock.sleeps
_ <- ZIO.debug(s"before: $before")
_ <- ZIO.debug(s"after: $after")
_ <- ZIO.debug(s"done: $done")
_ <- fiber2.join
} yield assertTrue(done.isEmpty)

The test prints the following output:

before: List(1970-01-01T00:00:05Z, 1970-01-01T00:00:10Z)
after: List(1970-01-01T00:00:05Z, 1970-01-01T00:00:10Z)
done: List()

The interrupted sleep of fiber1, which ends at 00:00:10, is still in the list after fiber1.interrupt. It is removed when the second adjust moves the clock past its end time.

Time Zoneโ€‹

The test clock runs in the UTC time zone. TestClock.setTimeZone changes the zone that Clock.currentDateTime and Clock.localDateTime use, and TestClock.timeZone returns it. Setting the zone neither changes the instant of the clock nor resumes any sleeping fiber:

import zio._
import zio.test._
import java.time.ZoneId

for {
_ <- TestClock.setTimeZone(ZoneId.of("Asia/Tehran"))
zone <- TestClock.timeZone
local <- Clock.localDateTime
now <- Clock.instant
} yield assertTrue(
zone == ZoneId.of("Asia/Tehran"),
local.toString == "1970-01-01T03:30",
now == java.time.Instant.EPOCH
)

Saving and Restoring the Stateโ€‹

TestClock.save returns an effect that restores the clock time, the time zone and the pending sleeps to the values they had when save was called. A sleep that started after the save is dropped from the pending sleeps when the state is restored, and later adjustments do not resume its fiber. The TestAspect.restoreTestClock aspect is built on this operation:

import zio._
import zio.test._
import java.time.Instant

for {
restore <- TestClock.save
_ <- TestClock.adjust(1.hour)
during <- Clock.instant
_ <- restore
after <- Clock.instant
} yield assertTrue(
during == Instant.parse("1970-01-01T01:00:00Z"),
after == Instant.EPOCH
)

Warningsโ€‹

TestClock logs two warnings when a test is likely to hang.

The first warning is logged when a test reads the clock or sleeps, and does not call TestClock.adjust or TestClock.setTime within 5 seconds of real time. The warning goes away for the rest of the test once the test adjusts or sets the clock. For example, a test that calls Clock.instant and then waits for 6 seconds of real time logs this line:

message="Warning: A test is using time, but is not advancing the test clock, which may result in the test hanging. Use TestClock.adjust to manually advance the time." location=<empty>.P2.spec file=P2.scala line=18

The location and file fields of the line depend on the test that logged it.

The second warning is related to how TestClock.adjust works. Before it moves the clock, and again after it resumes each sleeping fiber, adjust waits until the other fibers of the test are done or suspended. If the statuses of the suspended fibers keep changing and the fibers have not settled after 5 seconds of real time, adjust logs this warning:

Warning: A test is advancing the test clock, but a fiber is not suspending, which may result in the test hanging. Use TestAspect.diagnose to identity the fiber that is not suspending.

The TestAspect.diagnose aspect prints a fiber dump of a test that has not terminated within a given duration, so we can find the fiber that does not suspend.

Layers and Other Constructorsโ€‹

The testEnvironment layer builds a TestClock and installs it as the default Clock service. To build one on its own, we can use the following layers. TestClock.default and TestClock.live(data) need the Live and Annotations services, and TestClock.any needs only a TestClock:

  • TestClock.default starts the clock at the epoch (1970-01-01T00:00:00Z) in the UTC time zone, with no pending sleeps.
  • TestClock.live(data) starts from a TestClock.Data(instant, sleeps, timeZone) of our choice.
  • TestClock.any passes on the TestClock that its input environment already has.

The Clock service has two methods for code that uses Java time or a scheduler, and TestClock implements both on top of its own clock:

  • Clock.javaClock returns a java.time.Clock backed by the TestClock. Its instant() reads the clock time on each call, so it follows later adjustments, and its zone is the time zone at the moment javaClock runs.
  • Clock.scheduler returns a Scheduler driven by the TestClock. A task scheduled with a delay runs once adjust or setTime moves the clock to or past the time of scheduling plus the delay. On the JVM and Scala Native its asScheduledExecutorService runs its tasks on the TestClock as well.

For example, a java.time.Clock that we hand to some Java code follows the adjustments of the test:

import zio._
import zio.test._

for {
clock <- Clock.javaClock
before = clock.instant()
_ <- TestClock.adjust(1.minute)
after = clock.instant()
} yield assertTrue(
before == java.time.Instant.EPOCH,
after == java.time.Instant.parse("1970-01-01T00:01:00Z")
)

Examplesโ€‹

Example 1โ€‹

Thanks to the call to TestClock.adjust(1.minute) we moved the time instantly 1 minute.

import zio._
import zio.test.{test, _}
import java.util.concurrent.TimeUnit
import zio.Clock.currentTime

test("One can move time very fast") {
for {
startTime <- currentTime(TimeUnit.SECONDS)
_ <- TestClock.adjust(1.minute)
endTime <- currentTime(TimeUnit.SECONDS)
} yield assertTrue((endTime - startTime) >= 60L)
}

Example 2โ€‹

TestClock affects also all code running asynchronously that is scheduled to run after a certain time:

import zio._
import zio.test.{test, _}

test("One can control time as we see fit") {
for {
promise <- Promise.make[Unit, Int]
_ <- (ZIO.sleep(10.seconds) *> promise.succeed(1)).fork
_ <- TestClock.adjust(10.seconds)
readRef <- promise.await
} yield assertTrue(1 == readRef)
}

The above code creates a write-once cell that will be set to "1" after 10 seconds asynchronously from a different fiber thanks to the call to fork. In the end, we wait on the promise until it is set.

With the call to TestClock.adjust(10.seconds) we simulate the passing of 10 seconds of time. Because of it, we don't need to wait for the real 10 seconds to pass and thus our unit test can run faster.

This is a pattern that will very often be used when sleep and TestClock are being used for testing of effects that are based on time. The fiber that needs to sleep will be forked and TestClock will be used to adjust the time so that all expected effects are run in the forked fiber.

Example 3โ€‹

A more complex example leveraging dependencies and multiple services is shown below:

import zio.test.Assertion._
import zio.test._
import zio.{test => _, _}

trait SchedulingService {
def schedule(promise: Promise[Unit, Int]): ZIO[Any, Exception, Boolean]
}

trait LoggingService {
def log(msg: String): ZIO[Any, Exception, Unit]
}

val schedulingLayer: ZLayer[LoggingService, Nothing, SchedulingService] =
ZLayer.fromFunction { (loggingService: LoggingService) =>
new SchedulingService {
def schedule(promise: Promise[Unit, Int]): ZIO[Any, Exception, Boolean] =
(ZIO.sleep(10.seconds) *> promise.succeed(1))
.tap(b => loggingService.log(b.toString))
}
}

test("One can control time for failing effects too") {
val failingLogger = ZLayer.succeed(new LoggingService {
override def log(msg: String): ZIO[Any, Exception, Unit] = ZIO.fail(new Exception("BOOM"))
})

val layer = failingLogger >>> schedulingLayer

val testCase =
for {
promise <- Promise.make[Unit, Int]
result <- ZIO.serviceWithZIO[SchedulingService](_.schedule(promise)).exit.fork
_ <- TestClock.adjust(10.seconds)
readRef <- promise.await
result <- result.join
} yield assertTrue((1 == readRef) && result.isFailure)
testCase.provideLayer(layer)
}

In this case, we want to test an effect with dependencies that can potentially fail with an error. To do this we need to run the effect and use assertions that expect an Exit value.

Example 4โ€‹

The pattern with Promise and await can be generalized when we need to wait for multiple values using a Queue. We simply need to put multiple values into the queue and progress the clock multiple times and there is no need to create multiple promises.

Even if you have a non-trivial flow of data from multiple streams that can produce at different intervals and would like to test snapshots of data at a particular point in time Queue can help with that.

import zio._
import zio.test.{test, _}
import zio.stream._

test("zipLatest") {
val s1 = ZStream.iterate(0)(_ + 1).schedule(Schedule.fixed(100.milliseconds))
val s2 = ZStream.iterate(0)(_ + 1).schedule(Schedule.fixed(70.milliseconds))
val s3 = s1.zipLatest(s2)

for {
q <- Queue.unbounded[(Int, Int)]
_ <- s3.foreach(q.offer).fork
fiber <- ZIO.collectAll(ZIO.replicate(4)(q.take)).fork
_ <- TestClock.adjust(1.second)
result <- fiber.join
} yield assertTrue(result == List(0 -> 0, 0 -> 1, 1 -> 1, 1 -> 2))
}

Example 5โ€‹

TestClock is used to speed up the tests by simulating the passage of time. This is useful for triggering scheduled effects, which is useful for testing time-dependent code. TestClock does nothing to advance events on its own and is initialized to 00:00 1/1/70.

The test below creates a stream of 30 elements that are spaced 1 second apart. It forks the stream, advances the test clock by 30 seconds with a single call to TestClock.adjust, and joins the fiber to get all 30 elements:

import zio._
import zio.stream._
import zio.test.{test, _}

test("test clock") {
val stream = ZStream.iterate(0)(_ + 1).schedule(Schedule.spaced(1.second)).take(30)
for {
fiber <- stream.runCollect.fork
_ <- TestClock.adjust(30.seconds)
result <- fiber.join
} yield assertTrue(result.size == 30)
}

The clock does not jump to the end of the 30 seconds in one step. Before it moves the clock, TestClock.adjust waits until the other fibers of the test are done or suspended. Then it resumes the sleeping fibers one by one in the order of their end times, and after resuming each one it waits again until the fibers are suspended. The stream sleeps for 1 second between two elements, so the single call to adjust resumes the stream 30 times, and the stream takes each element before the clock reaches the next sleep. We neither need to adjust the clock 30 times nor to slow down the advancement with the live clock.

ZIO Chat

Hi there! ๐Ÿ‘‹ I'm ZIO Chat, your friendly neighborhood ZIO expert. I'm here to help you navigate the world of ZIO. Whether you're a seasoned pro or just starting out, fire away with your ZIO questions. I will hit you back with the best insights I've got. Let's dive into the world of ZIO together!