-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathAMQP.php
More file actions
423 lines (387 loc) · 11.5 KB
/
AMQP.php
File metadata and controls
423 lines (387 loc) · 11.5 KB
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
<?php
declare(strict_types=1);
namespace Codeception\Module;
use Codeception\Exception\ModuleException;
use Codeception\Lib\Interfaces\RequiresPackage;
use Codeception\Module;
use Codeception\TestInterface;
use Exception;
use PhpAmqpLib\Channel\AMQPChannel;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Exception\AMQPProtocolChannelException;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Wire\AMQPTable;
/**
* This module interacts with message broker software that implements
* the Advanced Message Queuing Protocol (AMQP) standard. For example, RabbitMQ (tested).
*
* <div class="alert alert-info">
* To use this module with Composer you need <em>"php-amqplib/php-amqplib": "~2.4"</em> package.
* </div>
*
* ## Config
*
* * host: localhost - host to connect
* * username: guest - username to connect
* * password: guest - password to connect
* * vhost: '/' - vhost to connect
* * cleanup: true - defined queues will be purged before running every test.
* * queues: [mail, twitter] - queues to cleanup
* * single_channel - create and use only one channel during test execution
* * reconnect - reconnects before each test to drop unused open channels
*
* ### Example
*
* modules:
* enabled:
* - AMQP:
* host: 'localhost'
* port: '5672'
* username: 'guest'
* password: 'guest'
* vhost: '/'
* queues: [queue1, queue2]
* single_channel: false
* reconnect: false
*
* ## Public Properties
*
* * connection - AMQPStreamConnection - current connection
*/
class AMQP extends Module implements RequiresPackage
{
protected array $config = [
'host' => 'localhost',
'username' => 'guest',
'password' => 'guest',
'port' => '5672',
'vhost' => '/',
'cleanup' => true,
'single_channel' => false,
'reconnect' => false,
'queues' => []
];
public ?AMQPStreamConnection $connection = null;
protected ?int $channelId = null;
/**
* @var string[]
*/
protected array $requiredFields = ['host', 'username', 'password', 'vhost'];
public function _requires(): array
{
return [AMQPStreamConnection::class => '"php-amqplib/php-amqplib": "~2.4"'];
}
public function _initialize(): void
{
$host = $this->config['host'];
$port = $this->config['port'];
$username = $this->config['username'];
$password = $this->config['password'];
$vhost = $this->config['vhost'];
try {
$this->connection = new AMQPStreamConnection($host, $port, $username, $password, $vhost);
} catch (Exception $exception) {
throw new ModuleException(__CLASS__, $exception->getMessage() . ' while establishing connection to MQ server');
}
}
public function _before(TestInterface $test): void
{
if ($this->config['cleanup']) {
$this->cleanup();
}
if ($this->config['reconnect']) {
$this->getChannel()->getConnection()->reconnect();
}
}
/**
* Sends message to exchange by sending exchange name, message
* and (optionally) a routing key
*
* ``` php
* <?php
* $I->pushToExchange('exchange.emails', 'thanks');
* $I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'));
* $I->pushToExchange('exchange.emails', new AMQPMessage('Thanks!'), 'severity');
* ```
*/
public function pushToExchange(string $exchange, string|AMQPMessage $message, ?string $routing_key = null): void
{
$message = $message instanceof AMQPMessage
? $message
: new AMQPMessage($message);
$this->getChannel()->basic_publish($message, $exchange, $routing_key);
}
/**
* Sends message to queue
*
* ``` php
* <?php
* $I->pushToQueue('queue.jobs', 'create user');
* $I->pushToQueue('queue.jobs', new AMQPMessage('create'));
* ```
*/
public function pushToQueue(string $queue, string|AMQPMessage $message): void
{
$message = $message instanceof AMQPMessage
? $message
: new AMQPMessage($message);
$this->getChannel()->queue_declare($queue);
$this->getChannel()->basic_publish($message, '', $queue);
}
/**
* Declares an exchange
*
* This is an alias of method `exchange_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
*
* ```php
* <?php
* $I->declareExchange(
* 'nameOfMyExchange', // exchange name
* 'topic' // exchange type
* )
* ```
*
* @return mixed
*/
public function declareExchange(
string $exchange,
string $type,
bool $passive = false,
bool $durable = false,
bool $auto_delete = true,
bool $internal = false,
bool $nowait = false,
array|AMQPTable|null $arguments = null,
?int $ticket = null
) {
return $this->getChannel()->exchange_declare(
$exchange,
$type,
$passive,
$durable,
$auto_delete,
$internal,
$nowait,
$arguments,
$ticket
);
}
/**
* Declares queue, creates if needed
*
* This is an alias of method `queue_declare` of `PhpAmqpLib\Channel\AMQPChannel`.
*
* ```php
* <?php
* $I->declareQueue(
* 'nameOfMyQueue', // exchange name
* )
* ```
*
* @return mixed
*/
public function declareQueue(
string $queue = '',
bool $passive = false,
bool $durable = false,
bool $exclusive = false,
bool $auto_delete = true,
bool $nowait = false,
array|AMQPTable|null $arguments = null,
?int $ticket = null
): ?array {
return $this->getChannel()->queue_declare(
$queue,
$passive,
$durable,
$exclusive,
$auto_delete,
$nowait,
$arguments,
$ticket
);
}
/**
* Binds a queue to an exchange
*
* This is an alias of method `queue_bind` of `PhpAmqpLib\Channel\AMQPChannel`.
*
* ```php
* <?php
* $I->bindQueueToExchange(
* 'nameOfMyQueueToBind', // name of the queue
* 'transactionTracking.transaction', // exchange name to bind to
* 'your.routing.key' // Optionally, provide a binding key
* )
* ```
*
* @return mixed
*/
public function bindQueueToExchange(
string $queue,
string $exchange,
string $routing_key = '',
bool $nowait = false,
array|AMQPTable|null $arguments = null,
?int $ticket = null
) {
return $this->getChannel()->queue_bind(
$queue,
$exchange,
$routing_key,
$nowait,
$arguments,
$ticket
);
}
/**
* Add a queue to purge list
*/
public function scheduleQueueCleanup(string $queue): void
{
if (!in_array($queue, $this->config['queues'])) {
$this->config['queues'][] = $queue;
}
}
/**
* Checks if message containing text received.
*
* **This method drops message from queue**
* **This method will wait for message. If none is sent the script will stuck**.
*
* ``` php
* <?php
* $I->pushToQueue('queue.emails', 'Hello, davert');
* $I->seeMessageInQueueContainsText('queue.emails','davert');
* ```
*/
public function seeMessageInQueueContainsText(string $queue, string $text): void
{
$msg = $this->getChannel()->basic_get($queue);
if (!$msg instanceof AMQPMessage) {
$this->fail("Message was not received");
}
if (!$msg instanceof AMQPMessage) {
$this->fail("Received message is not format of AMQPMessage");
}
$this->debugSection("Message", $msg->body);
$this->assertStringContainsString($text, $msg->body);
$msg->ack();
}
/**
* Count messages in queue.
*/
public function _countMessage(string $queue): int
{
[$queue, $messageCount] = $this->getChannel()->queue_declare($queue, true);
return $messageCount;
}
/**
* Checks that queue have expected number of message
*
* ``` php
* <?php
* $I->pushToQueue('queue.emails', 'Hello, davert');
* $I->seeNumberOfMessagesInQueue('queue.emails',1);
* ```
*/
public function seeNumberOfMessagesInQueue(string $queue, int $expected): void
{
$messageCount = $this->_countMessage($queue);
$this->assertEquals($expected, $messageCount);
}
/**
* Checks that queue is empty
*
* ``` php
* <?php
* $I->pushToQueue('queue.emails', 'Hello, davert');
* $I->purgeQueue('queue.emails');
* $I->seeQueueIsEmpty('queue.emails');
* ```
*/
public function seeQueueIsEmpty(string $queue): void
{
$messageCount = $this->_countMessage($queue);
$this->assertEquals(0, $messageCount);
}
/**
* Checks if queue is not empty.
*
* ``` php
* <?php
* $I->pushToQueue('queue.emails', 'Hello, davert');
* $I->dontSeeQueueIsEmpty('queue.emails');
* ```
*/
public function dontSeeQueueIsEmpty(string $queue): void
{
$messageCount = $this->_countMessage($queue);
$this->assertNotEquals(0, $messageCount);
}
/**
* Takes last message from queue.
*
* ``` php
* <?php
* $message = $I->grabMessageFromQueue('queue.emails');
* ```
*/
public function grabMessageFromQueue(string $queue): ?AMQPMessage
{
return $this->getChannel()->basic_get($queue);
}
/**
* Purge a specific queue defined in config.
*
* ``` php
* <?php
* $I->purgeQueue('queue.emails');
* ```
*/
public function purgeQueue(string $queueName = ''): void
{
if (! in_array($queueName, $this->config['queues'])) {
throw new ModuleException(__CLASS__, "'{$queueName}' doesn't exist in queues config list");
}
$this->getChannel()->queue_purge($queueName, true);
}
/**
* Purge all queues defined in config.
*
* ``` php
* <?php
* $I->purgeAllQueues();
* ```
*/
public function purgeAllQueues(): void
{
$this->cleanup();
}
protected function getChannel(): AMQPChannel
{
if ($this->config['single_channel'] && $this->channelId === null) {
$this->channelId = $this->connection->get_free_channel_id();
}
return $this->connection->channel($this->channelId);
}
protected function cleanup(): void
{
if (!isset($this->config['queues'])) {
throw new ModuleException(__CLASS__, "please set queues for cleanup");
}
if (!$this->connection) {
return;
}
foreach ($this->config['queues'] as $queue) {
try {
$this->getChannel()->queue_purge($queue);
} catch (AMQPProtocolChannelException $exception) {
// ignore if exchange/queue doesn't exist and rethrow exception if it's something else
if ($exception->getCode() !== 404) {
throw $exception;
}
}
}
}
}