2017-12-13 22:58:26 +01:00
|
|
|
<?php
|
|
|
|
|
2017-12-13 23:36:35 +01:00
|
|
|
namespace Amp\ParallelFunctions\Test;
|
2017-12-13 22:58:26 +01:00
|
|
|
|
|
|
|
use Amp\MultiReasonException;
|
2022-02-01 13:33:52 +01:00
|
|
|
use Amp\PHPUnit\AsyncTestCase;
|
2022-02-02 23:04:43 +01:00
|
|
|
use function Amp\ParallelFunctions\parallelMap;
|
2017-12-13 22:58:26 +01:00
|
|
|
use function Amp\Promise\wait;
|
|
|
|
|
2022-02-02 23:04:43 +01:00
|
|
|
class MapTest extends AsyncTestCase
|
|
|
|
{
|
|
|
|
public function testValidInput()
|
|
|
|
{
|
2017-12-14 17:01:25 +01:00
|
|
|
$this->assertSame([3, 4, 5], wait(parallelMap([1, 2, 3], function ($input) {
|
2017-12-13 22:58:26 +01:00
|
|
|
return $input + 2;
|
|
|
|
})));
|
|
|
|
}
|
|
|
|
|
2022-02-02 23:04:43 +01:00
|
|
|
public function testCorrectOutputOrder()
|
|
|
|
{
|
2017-12-17 19:31:34 +01:00
|
|
|
$this->assertSame([0, 1, 0], wait(parallelMap([0, 1, 0], function ($input) {
|
2017-12-17 19:33:29 +01:00
|
|
|
\sleep($input);
|
2017-12-17 19:31:34 +01:00
|
|
|
|
|
|
|
return $input;
|
|
|
|
})));
|
|
|
|
}
|
|
|
|
|
2022-02-02 23:04:43 +01:00
|
|
|
public function testException()
|
|
|
|
{
|
2017-12-13 22:58:26 +01:00
|
|
|
$this->expectException(MultiReasonException::class);
|
|
|
|
|
2017-12-14 17:01:25 +01:00
|
|
|
wait(parallelMap([1, 2, 3], function () {
|
2017-12-13 22:58:26 +01:00
|
|
|
throw new \Exception;
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2022-02-02 23:04:43 +01:00
|
|
|
public function testExecutesAllTasksOnException()
|
|
|
|
{
|
2017-12-13 22:58:26 +01:00
|
|
|
$files = [
|
2017-12-13 23:36:35 +01:00
|
|
|
[0, \tempnam(\sys_get_temp_dir(), 'amp-parallel-functions-')],
|
|
|
|
[1, \tempnam(\sys_get_temp_dir(), 'amp-parallel-functions-')],
|
|
|
|
[2, \tempnam(\sys_get_temp_dir(), 'amp-parallel-functions-')],
|
2017-12-13 22:58:26 +01:00
|
|
|
];
|
|
|
|
|
|
|
|
try {
|
2017-12-14 17:01:25 +01:00
|
|
|
wait(parallelMap($files, function ($args) {
|
2017-12-13 22:58:26 +01:00
|
|
|
list($id, $filename) = $args;
|
|
|
|
|
|
|
|
if ($id === 0) {
|
|
|
|
throw new \Exception;
|
|
|
|
}
|
|
|
|
|
|
|
|
\sleep(1);
|
|
|
|
\file_put_contents($filename, $id);
|
|
|
|
}));
|
|
|
|
|
|
|
|
$this->fail('No exception thrown.');
|
|
|
|
} catch (MultiReasonException $e) {
|
|
|
|
$this->assertStringEqualsFile($files[1][1], '1');
|
|
|
|
$this->assertStringEqualsFile($files[2][1], '2');
|
|
|
|
}
|
|
|
|
}
|
2017-12-13 23:48:03 +01:00
|
|
|
}
|