-
-
Notifications
You must be signed in to change notification settings - Fork 251
/
ProducerTest.php
117 lines (96 loc) 路 3.08 KB
/
ProducerTest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
namespace Amp\Test;
use Amp\Deferred;
use Amp\Loop;
use Amp\Pause;
use Amp\Producer;
use PHPUnit\Framework\TestCase;
class ProducerTest extends TestCase {
const TIMEOUT = 100;
/**
* @expectedException \Error
* @expectedExceptionMessage The callable did not return a Generator
*/
public function testNonGeneratorCallable() {
new Producer(function () {});
}
public function testEmit() {
Loop::run(function () {
$value = 1;
$producer = new Producer(function (callable $emit) use ($value) {
yield $emit($value);
});
$this->assertTrue(yield $producer->advance());
$this->assertSame($producer->getCurrent(), $value);
});
}
/**
* @depends testEmit
*/
public function testEmitSuccessfulPromise() {
Loop::run(function () {
$deferred = new Deferred();
$producer = new Producer(function (callable $emit) use ($deferred) {
yield $emit($deferred->promise());
});
$value = 1;
$deferred->resolve($value);
$this->assertTrue(yield $producer->advance());
$this->assertSame($producer->getCurrent(), $value);
});
}
/**
* @depends testEmitSuccessfulPromise
*/
public function testEmitFailedPromise() {
$exception = new \Exception;
Loop::run(function () use ($exception) {
$deferred = new Deferred();
$producer = new Producer(function (callable $emit) use ($deferred) {
return yield $emit($deferred->promise());
});
$deferred->fail($exception);
try {
yield $producer->advance();
} catch (\Exception $reason) {
$this->assertSame($reason, $exception);
}
});
}
/**
* @depends testEmit
*/
public function testEmitBackPressure() {
$emits = 3;
Loop::run(function () use (&$time, $emits) {
$producer = new Producer(function (callable $emit) use (&$time, $emits) {
$time = microtime(true);
for ($i = 0; $i < $emits; ++$i) {
yield $emit($i);
}
$time = microtime(true) - $time;
});
while (yield $producer->advance()) {
yield new Pause(self::TIMEOUT);
}
});
$this->assertGreaterThan(self::TIMEOUT * $emits - 1 /* 1ms grace period */, $time * 1000);
}
/**
* @depends testEmit
*/
public function testProducerCoroutineThrows() {
$exception = new \Exception;
try {
Loop::run(function () use ($exception) {
$producer = new Producer(function (callable $emit) use ($exception) {
yield $emit(1);
throw $exception;
});
while (yield $producer->advance());
});
} catch (\Exception $caught) {
$this->assertSame($exception, $caught);
}
}
}