|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Clients\Consumer; |
| 6 | + |
| 7 | +use Exception; |
| 8 | +use PHPUnit\Framework\TestCase; |
| 9 | +use SimPod\Kafka\Clients\Consumer\ConsumerConfig; |
| 10 | +use SimPod\Kafka\Clients\Consumer\KafkaConsumer; |
| 11 | +use SimPod\Kafka\Tests\Clients\Consumer\TestProducer; |
| 12 | + |
| 13 | +use function mt_rand; |
| 14 | +use function Safe\gethostname; |
| 15 | + |
| 16 | +use const RD_KAFKA_RESP_ERR__PARTITION_EOF; |
| 17 | +use const RD_KAFKA_RESP_ERR__TIMED_OUT; |
| 18 | +use const RD_KAFKA_RESP_ERR_NO_ERROR; |
| 19 | + |
| 20 | +final class KafkaTest extends TestCase |
| 21 | +{ |
| 22 | + public function testProduceConsume(): void |
| 23 | + { |
| 24 | + $topic = 'produce-consume'; |
| 25 | + $headers = ['key' => 'value']; |
| 26 | + |
| 27 | + $testProducer = new TestProducer(); |
| 28 | + $testProducer->run($topic, 'test', $headers); |
| 29 | + |
| 30 | + unset($testProducer); |
| 31 | + |
| 32 | + $consumer = new KafkaConsumer($this->getConfig()); |
| 33 | + $consumer->subscribe([$topic]); |
| 34 | + |
| 35 | + while (true) { |
| 36 | + $message = $consumer->consume(5000); |
| 37 | + switch ($message->err) { |
| 38 | + case RD_KAFKA_RESP_ERR_NO_ERROR: |
| 39 | + self::assertSame($message->headers, $headers); |
| 40 | + |
| 41 | + break 2; |
| 42 | + // phpcs:ignore PSR2.ControlStructures.SwitchDeclaration.TerminatingComment |
| 43 | + case RD_KAFKA_RESP_ERR__PARTITION_EOF: |
| 44 | + self::fail('No more messages; will wait for more'); |
| 45 | + // phpcs:ignore PSR2.ControlStructures.SwitchDeclaration.TerminatingComment |
| 46 | + case RD_KAFKA_RESP_ERR__TIMED_OUT: |
| 47 | + self::fail('Timed out'); |
| 48 | + default: |
| 49 | + throw new Exception($message->errstr(), $message->err); |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private function getConfig(): ConsumerConfig |
| 55 | + { |
| 56 | + $consumerConfig = new ConsumerConfig(); |
| 57 | + $consumerConfig->set(ConsumerConfig::BOOTSTRAP_SERVERS_CONFIG, '127.0.0.1:9092'); |
| 58 | + $consumerConfig->set(ConsumerConfig::CLIENT_ID_CONFIG, gethostname()); |
| 59 | + $consumerConfig->set(ConsumerConfig::GROUP_ID_CONFIG, mt_rand()); |
| 60 | + $consumerConfig->set(ConsumerConfig::AUTO_OFFSET_RESET_CONFIG, 'earliest'); |
| 61 | + |
| 62 | + return $consumerConfig; |
| 63 | + } |
| 64 | +} |
0 commit comments