Skip to content

Instantly share code, notes, and snippets.

@cspray
Last active June 20, 2018 23:24
Show Gist options
  • Save cspray/88ce3d550a0e5ac74c5cafbc5b85df95 to your computer and use it in GitHub Desktop.
Save cspray/88ce3d550a0e5ac74c5cafbc5b85df95 to your computer and use it in GitHub Desktop.
<?php
abstract class AsyncTestCase extends \PHPUnit\Framework\TestCase {
public function runTest() {
Loop::run(function() {
$watcherId = Loop::delay(1500, function() {
Loop::stop();
$this->fail('The asynchronous test was expected to finish before the 1500 millisecond time limit');
});
$testReturn = parent::runTest();
if (!$testReturn instanceof Promise) {
$testReturn = new Success($testReturn);
}
yield $testReturn;
Loop::cancel($watcherId);
});
}
}
<?php
class SomeAsyncTest extends AsyncTestCase {
public function testTriggeringMultipleEventListeners() {
$testContext = new TestContext();
$testContext->requireCheckpoints(3);
$subject = new EventBus();
$subject->subscribe('foo', function($eventData) use($testContext) {
// assert something about the state of the event data
$testContext->checkpoint();
});
$subject->subscribe('foo', function($eventData) use($testContext) {
// assert something about the state of the event data
$testContext->checkpoint();
});
$subject->subscribe('foo', function($eventData) use($testContext) {
// assert something about the state of the event data
$testContext->checkpoint(); // Promise returned below would resolve here or fail in 1500ms
});
$subject->publish('foo', ['event', 'data']);
// the $testContext acts like a Deferred and we can use it as such
return $testContext->promise();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment