Add SubscriberTest

This commit is contained in:
2021-01-23 02:59:33 +03:00
parent 6e37bbd1ae
commit 5d407480db
2 changed files with 51 additions and 1 deletions

View File

@ -12,6 +12,7 @@ final class Subscriber
{ {
public const STOP = 0; public const STOP = 0;
public const CHANGE_TIMEOUT = 1; public const CHANGE_TIMEOUT = 1;
public const TIMEOUT = 2;
private Consumer $reader; private Consumer $reader;
@ -21,7 +22,7 @@ final class Subscriber
} }
/** /**
* @psalm-return Generator<int, Message|null, int|float|null, void> * @psalm-return Generator<int, Message|float|null, int|float|null, void>
*/ */
public function subscribe(string $topic, string $channel, float $timeout = 0): Generator public function subscribe(string $topic, string $channel, float $timeout = 0): Generator
{ {
@ -45,6 +46,10 @@ final class Subscriber
$timeout = $newTimeout; $timeout = $newTimeout;
} }
if (self::TIMEOUT === $command) {
yield $timeout;
}
} }
$this->reader->disconnect(); $this->reader->disconnect();

45
tests/SubscriberTest.php Normal file
View File

@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
use Nsq\Consumer;
use Nsq\Subscriber;
use PHPUnit\Framework\TestCase;
final class SubscriberTest extends TestCase
{
private Subscriber $subscriber;
protected function setUp(): void
{
$consumer = new Consumer(
address: 'tcp://localhost:4150',
);
$this->subscriber = new Subscriber($consumer);
}
public function testChangeInterval(): void
{
$generator = $this->subscriber->subscribe(__FUNCTION__, __FUNCTION__, 0.1);
self::assertSame(0.1, $generator->send(Subscriber::TIMEOUT));
$generator->next();
$generator->send(Subscriber::CHANGE_TIMEOUT);
$generator->send(0.2);
self::assertSame(0.2, $generator->send(Subscriber::TIMEOUT));
}
public function testInvalidChangeInterval(): void
{
$this->expectException(\Nsq\Exception::class);
$this->expectExceptionMessage('Timeout must be float, "string" given.');
$generator = $this->subscriber->subscribe(__FUNCTION__, __FUNCTION__);
$generator->send(Subscriber::CHANGE_TIMEOUT);
// @phpstan-ignore-next-line
$generator->send('bla');
}
}