Extract components and add more tests

This commit is contained in:
2020-12-12 02:11:05 +01:00
parent 600f52567f
commit 92bc0ab407
22 changed files with 598 additions and 149 deletions

View File

@@ -11,17 +11,17 @@ class ConcurrencyLimitTest extends TestCase
{
use PropertyInspector;
public function testItDoesNotAllowZeroAsLimit(): void
public function testItDoesNotAcceptZero(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected -1 or positive integer, got \'0\'');
new ConcurrencyLimit(0);
ConcurrencyLimit::atMost(0);
}
public function testItDoesAllowNegativeOneAsLimit(): void
public function testItAcceptsNegativeOneAsUnlimited(): void
{
$limit = new ConcurrencyLimit(-1);
$limit = ConcurrencyLimit::atMost(-1);
self::assertTrue($limit->isUnlimited());
}
@@ -30,22 +30,22 @@ class ConcurrencyLimitTest extends TestCase
* @param int $negativeNumber
* @dataProvider negativeValueProvider
*/
public function testItDoesNotAllowAnyOtherNegativeNumberAsLimitExceptNegativeOne(int $negativeNumber): void
public function testItDoesNotAllowAnyOtherNegativeValue(int $negativeNumber): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('Expected -1 or positive integer, got \'%s\'', $negativeNumber));
new ConcurrencyLimit($negativeNumber);
ConcurrencyLimit::atMost($negativeNumber);
}
public function testItCanBeMadeUnlimited(): void
public function testTheLimitMayBeUnlimited(): void
{
$limit = ConcurrencyLimit::unlimited();
self::assertTrue($limit->isUnlimited());
}
public function testItCanLimitToASingleWorker(): void
public function testTheLimitMayBeASingleWorker(): void
{
$limit = ConcurrencyLimit::singleWorker();
@@ -64,8 +64,8 @@ class ConcurrencyLimitTest extends TestCase
public function testABoundLimitCanBeReached(): void
{
$three = new ConcurrencyLimit(3);
$seven = new ConcurrencyLimit(7);
$three = ConcurrencyLimit::atMost(3);
$seven = ConcurrencyLimit::atMost(7);
self::assertTrue($three->isReachedBy(3));
self::assertFalse($three->isReachedBy(2));

View File

@@ -7,6 +7,7 @@ use React\EventLoop\LoopInterface;
use Toalett\Multiprocessing\ConcurrencyLimit;
use Toalett\Multiprocessing\ContextBuilder;
use Toalett\Multiprocessing\Tests\Tools\PropertyInspector;
use Toalett\Multiprocessing\Workers;
class ContextBuilderTest extends TestCase
{
@@ -22,14 +23,14 @@ class ContextBuilderTest extends TestCase
self::assertNotSame($builder->withLimit($limit), $builder);
}
public function testItGivesBackANewContextEachTimeBuildIsInvoked(): void
public function testItBuildsANewContextEveryTime(): void
{
$builder = ContextBuilder::create();
self::assertNotSame($builder->build(), $builder->build());
}
public function testItCreatesANewContextWithUnlimitedConcurrencyWhenSupplyingNoArguments(): void
public function testTheDefaultConcurrencyLimitIsUnlimited(): void
{
$builder = ContextBuilder::create();
@@ -44,7 +45,7 @@ class ContextBuilderTest extends TestCase
self::assertTrue($limit->isUnlimited());
}
public function testWhenSuppliedWithACustomEventLoopItUsesThatEventLoop(): void
public function testWhenGivenAnEventLoopItUsesThatLoop(): void
{
$builder = ContextBuilder::create();
$eventLoop = $this->createMock(LoopInterface::class);
@@ -55,7 +56,7 @@ class ContextBuilderTest extends TestCase
self::assertSame($eventLoop, $usedEventLoop);
}
public function testWhenSuppliedWithACustomConcurrencyLimitItUsesThatLimit(): void
public function testWhenGivenAConcurrencyLimitItUsesThatLimit(): void
{
$builder = ContextBuilder::create();
$limit = $this->createMock(ConcurrencyLimit::class);
@@ -65,4 +66,15 @@ class ContextBuilderTest extends TestCase
self::assertSame($limit, $usedLimit);
}
public function testWhenGivenWorkersItUsesThatWorkers(): void
{
$builder = ContextBuilder::create();
$workers = $this->createMock(Workers::class);
$context = $builder->withWorkers($workers)->build();
$usedWorkers = $this->getProperty($context, 'workers');
self::assertSame($workers, $usedWorkers);
}
}

View File

@@ -5,6 +5,7 @@ namespace Toalett\Multiprocessing\Tests;
use PHPUnit\Framework\TestCase;
use React\EventLoop\Factory;
use React\EventLoop\LoopInterface;
use React\EventLoop\Timer\Timer;
use Toalett\Multiprocessing\ConcurrencyLimit;
use Toalett\Multiprocessing\Context;
use Toalett\Multiprocessing\Workers;
@@ -36,21 +37,24 @@ class ContextTest extends TestCase
$context = new Context($loop, $limit);
$limit->method('isReachedBy')->willReturn(true); // trigger congestion
$loop->futureTick(fn() => $context->stop());
$congestionEventHasTakenPlace = false;
$congestionRelievedEventHasTakenPlace = false;
$context->on('congestion', function () use (&$congestionEventHasTakenPlace) {
$congestionEventHasTakenPlace = true;
});
$congestionRelievedEventHasTakenPlace = false;
$context->on('congestion_relieved', function () use (&$congestionRelievedEventHasTakenPlace) {
$congestionRelievedEventHasTakenPlace = true;
});
self::assertFalse($congestionEventHasTakenPlace);
self::assertFalse($congestionRelievedEventHasTakenPlace);
$context->submit(fn() => []);
$loop->futureTick(fn() => $context->stop());
$context->submit(static fn() => null);
$context->run();
self::assertTrue($congestionEventHasTakenPlace);
self::assertTrue($congestionRelievedEventHasTakenPlace);
}
@@ -62,36 +66,47 @@ class ContextTest extends TestCase
$context = new Context($loop, $limit);
$limit->method('isReachedBy')->willReturn(false);
$loop->expects(self::once())->method('futureTick')->withConsecutive(
[fn() => []],
);
$loop->expects(self::once())
->method('futureTick')
->withConsecutive([
static fn() => null,
]);
$context->submit(fn() => []);
$context->submit(static fn() => null);
}
public function testItRegistersMaintenanceCallbacksOnTheEventLoop(): void
public function testItRegistersMaintenanceTasksOnTheEventLoop(): void
{
$loop = $this->createMock(LoopInterface::class);
$limit = $this->createMock(ConcurrencyLimit::class);
$loop->expects(self::exactly(2))->method('addPeriodicTimer')->withConsecutive(
[Context::CLEANUP_INTERVAL, fn() => []],
[Context::GC_INTERVAL, fn() => []]
);
$loop->expects(self::exactly(2))
->method('addPeriodicTimer')
->withConsecutive(
[Context::INTERVAL_CLEANUP, static fn() => null],
[Context::INTERVAL_GC, static fn() => null]
)->willReturnOnConsecutiveCalls(
new Timer(Context::INTERVAL_CLEANUP, static fn() => null),
new Timer(Context::INTERVAL_GC, static fn() => null),
);
new Context($loop, $limit);
$context = new Context($loop, $limit);
$context->run();
}
public function testItProxiesWorkersEventsToSelf(): void
public function testItForwardsWorkersEventsToSelf(): void
{
$loop = $this->createMock(LoopInterface::class);
$limit = $this->createMock(ConcurrencyLimit::class);
$workers = $this->createMock(Workers::class);
$workers->expects(self::atLeast(2))->method('on')->withConsecutive(
['worker_started', fn() => []],
['worker_stopped', fn() => []]
);
$workers->expects(self::exactly(3))
->method('on')
->withConsecutive(
['worker_started', static fn() => null],
['worker_stopped', static fn() => null],
['no_workers_remaining', static fn() => null]
);
new Context($loop, $limit, $workers);
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Toalett\Multiprocessing\Tests\Task;
use Generator;
use PHPUnit\Framework\TestCase;
use Toalett\Multiprocessing\Exception\InvalidArgumentException;
use Toalett\Multiprocessing\Task\Interval;
class IntervalTest extends TestCase
{
/**
* @param $method
* @param $val
* @param $calculatedVal
* @dataProvider zeroAndDownProvider
*/
public function testItDoesNotAllowLessThanZeroOrZero($method, $val, $calculatedVal): void
{
$this->setName(sprintf('It does not allow %d for %s', $val, $method));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(sprintf('Expected positive float, got \'%s\'', $calculatedVal));
Interval::{$method}($val);
}
/**
* @param $method
* @param $val
* @param $expected
* @dataProvider oneAndUpProvider
*/
public function testItCalculatesTheCorrectInterval($method, $val, $expected): void
{
$this->setName('It calculates the correct interval in ' . $method);
$interval = Interval::{$method}($val);
self::assertEquals($expected, $interval->asFloat());
}
public function zeroAndDownProvider(): Generator
{
return $this->createProvider(0, -5, -9000);
}
public function oneAndUpProvider(): Generator
{
return $this->createProvider(1, 5, 7500);
}
public function createProvider(...$args): Generator
{
foreach ($args as $arg) {
yield "$arg seconds" => ['seconds', $arg, $arg];
yield "$arg minutes" => ['minutes', $arg, $arg * 60.0];
yield "$arg hours" => ['hours', $arg, $arg * 3600.0];
}
}
}

View File

@@ -0,0 +1,37 @@
<?php
namespace Toalett\Multiprocessing\Tests\Task;
use Generator;
use PHPUnit\Framework\TestCase;
use React\EventLoop\LoopInterface;
use React\EventLoop\Timer\Timer;
use Toalett\Multiprocessing\Task\Interval;
use Toalett\Multiprocessing\Task\RepeatedTask;
class RepeatedTaskTest extends TestCase
{
/**
* @param $interval
* @dataProvider dataProvider
*/
public function testItRegistersWithTheProvidedInterval(Interval $interval): void
{
$loop = $this->createMock(LoopInterface::class);
$loop->expects(self::once())
->method('addPeriodicTimer')
->with($interval->asFloat(), static fn() => null)
->willReturn(new Timer($interval->asFloat(), static fn() => null, true));
$task = new RepeatedTask($interval, static fn() => null);
$task->enable($loop);
}
public function dataProvider(): Generator
{
yield "3 seconds" => [Interval::seconds(3)];
yield "5 minutes" => [Interval::minutes(5)];
yield "half an hour" => [Interval::hours(0.5)];
yield "a day" => [Interval::hours(24)];
}
}

View File

@@ -0,0 +1,91 @@
<?php
namespace Toalett\Multiprocessing\Tests\Task;
use PHPUnit\Framework\MockObject\MockObject;
use React\EventLoop\LoopInterface;
use Toalett\Multiprocessing\Task\Task;
use Toalett\Multiprocessing\Task\Tasks;
use PHPUnit\Framework\TestCase;
use Toalett\Multiprocessing\Tests\Tools\PropertyInspector;
class TasksTest extends TestCase
{
use PropertyInspector;
public function testItAcceptsZeroTasks(): void
{
$this->expectNotToPerformAssertions();
new Tasks();
}
public function testItAcceptsMultipleTasks(): void
{
$this->expectNotToPerformAssertions();
new Tasks(
$this->createMock(Task::class),
$this->createMock(Task::class)
);
}
public function testItDoesNotReEnableWhenEnabled(): void
{
$loop = $this->createMock(LoopInterface::class);
$task = $this->createMock(Task::class);
$tasks = new Tasks($task);
$task->expects(self::once())
->method('enable')
->with($loop);
$tasks->enable($loop);
$tasks->enable($loop);
}
public function testItEnablesAllTasksWhenEnableCalled(): void
{
$loop = $this->createMock(LoopInterface::class);
$task1 = $this->createMock(Task::class);
$task2 = $this->createMock(Task::class);
$task3 = $this->createMock(Task::class);
foreach([$task1, $task2, $task3] as $task) {
/** @var MockObject|Task $task */
$task->expects(self::once())->method('enable')->with($loop);
}
(new Tasks($task1, $task2, $task3))->enable($loop);
}
public function testItCancelsAllTasksWhenCancelCalled(): void
{
$loop = $this->createMock(LoopInterface::class);
$task1 = $this->createMock(Task::class);
$task2 = $this->createMock(Task::class);
$task3 = $this->createMock(Task::class);
foreach([$task1, $task2, $task3] as $task) {
/** @var MockObject|Task $task */
$task->expects(self::once())->method('cancel')->with($loop);
}
$tasks = new Tasks($task1, $task2, $task3);
$this->setProperty($tasks, 'loop', $loop);
$tasks->cancel();
}
public function testItDoesNotCancelTasksWhenTheyAreNotEnabled(): void
{
$task1 = $this->createMock(Task::class);
$task2 = $this->createMock(Task::class);
$task3 = $this->createMock(Task::class);
foreach([$task1, $task2, $task3] as $task) {
/** @var MockObject|Task $task */
$task->expects(self::never())->method('cancel');
}
$tasks = new Tasks($task1, $task2, $task3);
$tasks->cancel();
}
}

View File

@@ -13,4 +13,12 @@ trait PropertyInspector
$property->setAccessible(true);
return $property->getValue($object);
}
protected function setProperty(object $object, string $propertyName, $value): void
{
$reflector = new ReflectionObject($object);
$property = $reflector->getProperty($propertyName);
$property->setAccessible(true);
$property->setValue($object, $value);
}
}

View File

@@ -49,8 +49,8 @@ class WorkersTest extends TestCase
$workers->on('worker_started', function () use (&$workerStartedEventHasTakenPlace) {
$workerStartedEventHasTakenPlace = true;
});
self::assertFalse($workerStartedEventHasTakenPlace);
self::assertFalse($workerStartedEventHasTakenPlace);
$workers->createWorkerFor(fn() => exit(0), []);
self::assertTrue($workerStartedEventHasTakenPlace);
}
@@ -72,6 +72,20 @@ class WorkersTest extends TestCase
self::assertTrue($workerStoppedEventHasTakenPlace);
}
public function testItEmitsAnEventWhenNoWorkersRemain(): void
{
$workers = new Workers();
$noWorkersRemainingEventHasTakenPlace = false;
$workers->on('no_workers_remaining', function () use (&$noWorkersRemainingEventHasTakenPlace) {
$noWorkersRemainingEventHasTakenPlace = true;
});
self::assertFalse($noWorkersRemainingEventHasTakenPlace);
$workers->cleanup();
self::assertTrue($noWorkersRemainingEventHasTakenPlace);
}
public function testItCallsForkOnProcessControlWhenAskedToCreateAWorker(): void
{
$processControl = $this->createMock(ProcessControl::class);
@@ -88,7 +102,7 @@ class WorkersTest extends TestCase
$processControl = $this->createMock(ProcessControl::class);
$processControl->expects(self::once())
->method('wait')
->with(WNOHANG)
->with(Wait::NO_HANG)
->willReturn(new Wait(0));
$workers = new Workers($processControl);