1
0
mirror of https://github.com/danog/amp.git synced 2024-12-12 09:29:45 +01:00
amp/test/CallTest.php

80 lines
1.8 KiB
PHP
Raw Normal View History

2017-02-22 22:52:30 +01:00
<?php
namespace Amp\Test;
2017-05-03 15:21:49 +02:00
use Amp\Failure;
2020-09-28 05:19:52 +02:00
use Amp\PHPUnit\AsyncTestCase;
2017-05-03 15:21:49 +02:00
use Amp\PHPUnit\TestException;
use Amp\Promise;
2017-04-23 14:39:19 +02:00
use Amp\Success;
2020-09-28 05:19:52 +02:00
use function Amp\await;
use function Amp\call;
2017-02-22 22:52:30 +01:00
2020-09-28 05:19:52 +02:00
class CallTest extends AsyncTestCase
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
public function testCallWithFunctionReturningPromise(): void
2018-06-18 20:00:01 +02:00
{
2017-02-22 22:52:30 +01:00
$value = 1;
2020-09-28 05:19:52 +02:00
$promise = call(function ($value) {
2017-02-22 22:52:30 +01:00
return new Success($value);
}, $value);
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($promise));
2017-02-22 22:52:30 +01:00
}
2020-09-28 05:19:52 +02:00
public function testCallWithFunctionReturningValue(): void
2018-06-18 20:00:01 +02:00
{
2017-02-22 22:52:30 +01:00
$value = 1;
2020-09-28 05:19:52 +02:00
$promise = call(function ($value) {
2017-02-22 22:52:30 +01:00
return $value;
}, $value);
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($promise));
2017-02-22 22:52:30 +01:00
}
2020-09-28 05:19:52 +02:00
public function testCallWithThrowingFunction(): void
2018-06-18 20:00:01 +02:00
{
2017-02-22 22:52:30 +01:00
$exception = new \Exception;
2020-09-28 05:19:52 +02:00
$promise = call(function () use ($exception) {
2017-02-22 22:52:30 +01:00
throw $exception;
});
$this->assertInstanceOf(Promise::class, $promise);
$promise->onResolve(function ($exception, $value) use (&$reason, &$result) {
2017-02-22 22:52:30 +01:00
$reason = $exception;
$result = $value;
});
2020-09-28 05:19:52 +02:00
try {
await($promise);
} catch (\Exception $reason) {
$this->assertSame($exception, $reason);
return;
}
$this->fail("Returned promise was not failed");
2017-02-22 22:52:30 +01:00
}
2018-06-18 20:00:01 +02:00
public function testCallWithGeneratorFunction()
{
2017-02-22 22:52:30 +01:00
$value = 1;
2020-09-28 05:19:52 +02:00
$promise = call(function ($value) {
2017-02-22 22:52:30 +01:00
return yield new Success($value);
}, $value);
2020-09-28 05:19:52 +02:00
$this->assertSame($value, await($promise));
2017-02-22 22:52:30 +01:00
}
2017-05-03 15:21:49 +02:00
2020-09-28 05:19:52 +02:00
public function testCallFunctionWithFailure()
2018-06-18 20:00:01 +02:00
{
2020-09-28 05:19:52 +02:00
$promise = call(function () {
2017-05-03 15:21:49 +02:00
return new Failure(new TestException);
2020-09-28 05:19:52 +02:00
});
2017-05-03 15:21:49 +02:00
$this->expectException(TestException::class);
2020-09-28 05:19:52 +02:00
await($promise);
2017-05-03 15:21:49 +02:00
}
2017-02-22 22:52:30 +01:00
}