Sleeping is not the best option
Tags: testing, php, webdev, refactoring
Published: 2022-12-05 10:49:18

---
title: "Sleeping is not the best option"
published: true
description: "An example of a technique that might be used to effectively test asynchronous code"
tags: 
  - testing
  - php
  - webdev 
  - refactoring
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i9jgq0xu5r6w24btd2j3.jpg
canonical_url: https://codesai.com/posts/2020/10/polling-and-probing
# Use a ratio of 100:42 for best results.
# published_at: 2022-12-05 10:38 +0000
---

<h2>Introduction. </h2>

Some time ago we were developing a code that stored some data with a given [TTL](https://en.wikipedia.org/wiki/Time_to_live). We wanted to check not only that the data was stored correctly but also that it expired after the given TTL. This is an example of testing asynchronous code.

When testing asynchronous code we need to carefully coordinate the test with the system it is testing to avoid running the assertion before the tested action has completed<a href="#nota1"><sup>[1]</sup></a>. For example, the following test will always fail because the assertion in line 30 is checked before the data has expired:

```php
<?php
namespace Trovit\B2B\AdClick\Tests\integration\Infrastructure;

use PHPUnit\Framework\TestCase;
// some other imports

class RedisDataProviderTest extends TestCase
{
    // some fields...

    /*** @test */
    public function data_expire_after_some_time()
    {
        $currentTimestamp = '2019-06-01 10:00:00';
        $this->clock->now()->willReturn($currentTimestamp);
        $dataProvider = new RedisDataProvider(
            new PhpRedisClient(), 
            $this->clock->reveal(),
            $this->tts
        );

        $data = $dataProvider->registerData($this->keyData, 1);

        $expectedData = [
            'data' => 1,
            'timestamp' => $currentTimestamp
        ];
        $this->assertEquals($expectedData, $data);
        $this->assertEquals($expectedData, $this->redis->hGetAll($this->key));
        // the following assertion will always fail
        $this->assertTrue(empty($this->redis->hGetAll($this->key)));
    }
    
    // other tests...
    
    public function setUp()
    {
        $this->keyData = 'some data';
        $this->key = 'data:' . $this->keyData;
        $this->tts = 1;
        $this->clock = $this->prophesize(Clock::class);
        $this->connectToRedis();
    }
}
```

In this case the test always fails but in other cases it might be worse, failing intermittently when the system is working, or passing when the system is broken. We need to make the test wait to give the action we are testing time to complete successfully and fail if this doesn't happen within a given timeout period.

<h2>Sleeping is not the best option.</h2>
This is an improved version of the previous test in which we are making the test code wait before the checking that the data has expired to give the code under test time to run:

```php
<?php
namespace Trovit\B2B\AdClick\Tests\integration\Infrastructure;

use PHPUnit\Framework\TestCase;
// some other imports

class RedisDataProviderTest extends TestCase
{
    // some fields...

    /** * @test */
    public function data_expire_after_some_time()
    {
        $currentTimestamp = '2019-06-01 10:00:00';
        $this->clock->now()->willReturn($currentTimestamp);
        $dataProvider = new RedisDataProvider(
            new PhpRedisClient(), 
            $this->clock->reveal(),
            $this->tts
        );

        $data = $dataProvider->registerData($this->keyData, 1);

        $expectedData = [
            'data' => 1,
            'timestamp' => $currentTimestamp
        ];
        $this->assertEquals($expectedData, $data);
        $this->assertEquals($expectedData, $this->redis->hGetAll($this->key));
        sleep(5.0); // <- waiting for the data to expire
        $this->assertTrue(empty($this->redis->hGetAll($this->key)));
    }
    
    // other tests...
    
    public function setUp()
    {
        $this->keyData = 'some data';
        $this->key = 'data:' . $this->keyData;
        $this->tts = 1;
        $this->clock = $this->prophesize(Clock::class);
        $this->connectToRedis();
    }
}
```

The problem with the simple sleeping approach is that in some runs the timeout might be enough for the data to expire but in other runs it might not, so the test will fail intermittently; it becomes a flickering test. Flickering tests are confusing because when they fail, we don't know whether it’s due to a real bug, or it is just a false positive. If the failure is relatively common, the team might start ignoring those tests which can mask real defects and completely destroy the value of having automated tests.

Since the intermittent failures happen because the timeout is too close to the time the behavior we are testing takes to run, many teams decide to reduce the frequency of those failures by increasing the time each test sleeps before checking that the action under test was successful. This is not practical because it soon leads to test suites that take too long to run.

<h2>Alternative approaches. </h2>

If we are able to detect success sooner, succeeding tests will provide rapid feedback, and we only have to wait for failing tests to timeout. This is a much better approach than waiting the same amount of time for each test regardless it fails or succeeds.

There are two main strategies to detect success sooner: **capturing notifications**<a href="#nota2"><sup>[2]</sup></a> and **polling for changes**.

In the case we are using as an example, polling was the only option because redis didn't send any monitoring events we could listen to.

<h2>Polling for changes. </h2>
To detect success as soon as possible, we're going to probe several times separated by a time interval which will be shorter than the previous timeout. If the result of a probe is what we expect the test pass, if the result we expect is not there yet, we sleep a bit and retry. If after several retries, the expected value is not there, the test will fail.

Have a look at the `checkThatDataHasExpired` method in the following code:

```php
<?php
namespace Trovit\B2B\AdClick\Tests\integration\Infrastructure;

use PHPUnit\Framework\TestCase;
// some other imports

class RedisDataProviderTest extends TestCase
{
    // some fields...
    
    /** * @test */
    public function data_expire_after_some_time()
    {
        $currentTimestamp = '2019-06-01 10:00:00';
        $this->clock->now()->willReturn($currentTimestamp);
        $dataProvider = new RedisDataProvider(
            new PhpRedisClient(), 
            $this->clock->reveal(),
            $this->tts
        );

        $data = $dataProvider->registerData($this->keyData, 1);

        $expectedData = [
            'data' => 1,
            'timestamp' => $currentTimestamp
        ];
        $this->assertEquals($expectedData, $data);
        $this->assertEquals($expectedData, $this->redis->hGetAll($this->key));
        $this->checkThatDataHasExpired();
    }
    
    private function checkThatDataHasExpired() 
    {
        $dataExpired = false;
        $sleepTime = $this->tts + 0.1;
        $numRetries = 3;
        while ($numProbes > 0) {
            sleep($sleepTime);
            if (empty($this->redis->hGetAll($this->key))) {
                $dataExpired = true;
            }
            $numProbes--;
        }
        $this->assertTrue( $dataExpired);
    }
    
    // other tests...
    
    public function setUp()
    {
        $this->keyData = 'some data';
        $this->key = 'data:' . $this->keyData;
        $this->tts = 1;
        $this->clock = $this->prophesize(Clock::class);
        $this->connectToRedis();
    }
}
```

By polling for changes we avoid always waiting the maximum amount of time. Only in the worst case scenario, when consuming all the retries without detecting success, we'll wait as much as in the just sleeping approach that used a fixed timeout.

<h2>Extracting a helper.</h2>

Scattering ad hoc low level code that polls and probes like the one in `checkThatDataHasExpired` throughout your tests not only make them difficult to understand, but also is a very bad case of duplication. So we extracted it to a helper so we could reuse it in different situations.

What varies from one application of this approach to another are **the probe**, **the check**, **the number of probes before failing** and **the time between probes**, everything else we extracted to the following helper<a href="#nota3"><sup>[3]</sup></a>:

```php
<?php
namespace Trovit\B2B\AdClick\Tests\helper;

use PHPUnit\Framework\Assert;

class AsyncTestHelpers
{
    public static function assertWithPolling(
        $sleepTime,
        $numProbes,
        $errorDescription,
        callable $probe,
        callable $check
    ) {
        Assert::assertTrue(
            self::pull($sleepTime, $numProbes, $probe, $check),
            $errorDescription
        );
    }

    private static function poll($sleepTime, $numProbes, callable $probe, callable $check)
    {
        while ($numProbes > 0) {
            sleep($sleepTime);
            $result = $probe();
            if ($check($result)) {
                return true;
            }
            $numProbes--;
        }
        return false;
    }
}
```

This is how the previous tests would look after using the helper:

```php
<?php
namespace Trovit\B2B\AdClick\Tests\integration\Infrastructure;

use PHPUnit\Framework\TestCase;
// some other imports

class RedisDataProviderTest extends TestCase
{
    // some fields...

    /*** @test */
    public function data_expire_after_some_time()
    {
        $currentTimestamp = '2019-06-01 10:00:00';
        $this->clock->now()->willReturn($currentTimestamp);
        $dataProvider = new RedisDataProvider(
            new PhpRedisClient(), 
            $this->clock->reveal(),
            $this->tts
        );

        $data = $dataProvider->registerData($this->keyData, 1);

        $expectedData = [
            'data' => 1,
            'timestamp' => $currentTimestamp
        ];
        $this->assertEquals($expectedData, $data);
        $this->assertEquals($expectedData, $this->redis->hGetAll($this->key));
        $this->checkThatDataHasExpired($this);
    }
    
    private function checkThatDataHasExpired($context) 
    {
        $probe = function () use ($context) {
            return $self->redis->hGetAll($context->key);
        };
        $check = function ($storedData) {
            return empty($storedData);
        };
        AsyncTestHelpers::assertWithPolling(
            $this->tts + 0.1,
            3,
            'Data redis key expiration has failed',
            $probe,
            $check
        );
    }
    
    // other tests
    
    public function setUp()
    {
        $this->keyData = 'some data';
        $this->key = 'data:' . $this->keyData;
        $this->tts = 1;
        $this->clock = $this->prophesize(Clock::class);
        $this->connectToRedis();
    }
}
```

Notice that we're passing the probe, the check, the number of probes and the sleep time between probes to the `AsyncTestHelpers::assertWithPolling` function.

<h2>Conclusions.</h2>

We showed an example in Php of an approach to test asynchronous code described by [Steve Freeman](https://www.higherorderlogic.com/) and [Nat Pryce](http://www.natpryce.com/) in their [Growing Object-Oriented Software, Guided by Tests](https://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests) book. This approach avoids flickering test and produces much faster test suites than using a fixed timeout. We also showed how we abstracted this approach by extracting a helper function that we are reusing in our code. 

We hope you've found this approach interesting. If you want to learn more about this and several other techniques to effectively test asynchronous code, have a look at the wonderful [Growing Object-Oriented Software, Guided by Tests](https://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests) book<a href="#nota4"><sup>[4]</sup></a>.

<h2>Acknowledgements.</h2>

Thanks to my Codesai colleagues for reading the initial drafts and giving me feedback and to [Chrisy Totty](https://www.pexels.com/@tottster) for the lovely cat picture.

<h2>Notes.</h2>

<div class="foot-note">
  <a name="nota1"></a> [1] This is a nice example of <i>Connascence of Timing (CoT)</i>. <i>CoT</i> happens when when the timing of the execution of multiple components is important. In this case the action being tested must run before the assertion that checks its observable effects. That's the coordination we talk about. Check <a href="https://codesai.com/2017/01/about-connascence">our post about Connascence</a> to learn more about this interesting topic.
</div>

<div class="foot-note">
  <a name="nota2"></a> [2] In the <i>capturing notifications</i> strategy the test code "observes the system by listening for events that the system sends out. An event-based assertion waits for an event by blocking on a monitor until gets notified or times out", (from <a href="https://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests">Growing Object-Oriented Software, Guided by Tests book</a>).<br> 

  Some time ago we developed <a href="https://gist.github.com/trikitrok/a39f5fbec6ab0ee0c6f8db68e87a552c#file-async-test-tools-cljs">some helpers using the <i>capturing notifications</i> strategy </a>to test asynchronous ClojureScript code that was using <a href="https://github.com/clojure/core.async">core.async</a> channels. Have a look at, for instance, the <code class="highlighter-rouge">expect-async-message</code> assertion helper in which we use <code class="highlighter-rouge">core.async/alts!</code> and <code class="highlighter-rouge">core.async/timeout</code> to implement this behaviour. The <code class="highlighter-rouge">core.async/alts!</code> function selects the first channel that responds. If that channel is the one the test code was observing we assert that the received message is what we expected. If the channel that responds first is the one generated by <code class="highlighter-rouge">core.async/timeout</code> we fail the test. We mentioned these <code class="highlighter-rouge">async-test-tools</code> in previous post: <a href="https://codesai.com/2017/06/testing-om-components">Testing Om components with cljs-react-test</a>.
</div>

<div class="foot-note">
  <a name="nota3"></a> [3] Have a look at the <a href="https://github.com/npryce/goos-code-examples/tree/master/testing-asynchronous-systems">testing asynchronous systems examples</a> in the <a href="https://github.com/npryce/goos-code-examples">GOOS Code examples repository</a> for a more object-oriented implementation of helper for the <i>polling for changes</i> strategy, and also examples of the <i>capturing notifications</i> strategy.
</div>

<div class="foot-note">
  <a name="nota4"></a> [4] Chapter 27, <i>Testing Asynchronous code</i>, contains a great explanation of the two main strategies to test asynchronous code effectively: <i>capturing notifications</i> and <i>polling for changes</i>.
</div>

<h2>References.</h2>

* [Growing Object-Oriented Software, Guided by Tests](https://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests), [Steve Freeman](https://www.higherorderlogic.com/) and [Nat Pryce](http://www.natpryce.com/) (chapter 27: <i>Testing Asynchronous Code</i>)

* [Eradicating Non-Determinism in Tests](https://martinfowler.com/articles/nonDeterminism.html#footnote-useful-nondeterminism), [Martin Fowler](https://martinfowler.com/)