From db560b26d240a8199dca2c7e06c273a548b9aa3b Mon Sep 17 00:00:00 2001 From: Timm Friebe Date: Sat, 18 Jan 2025 10:47:05 +0100 Subject: [PATCH] Add test for EventSource implementation --- src/main/php/web/io/EventSource.class.php | 10 ++++- .../web/unittest/io/EventSourceTest.class.php | 39 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100755 src/test/php/web/unittest/io/EventSourceTest.class.php diff --git a/src/main/php/web/io/EventSource.class.php b/src/main/php/web/io/EventSource.class.php index c25706f..519124f 100755 --- a/src/main/php/web/io/EventSource.class.php +++ b/src/main/php/web/io/EventSource.class.php @@ -3,7 +3,13 @@ use IteratorAggregate, Traversable; use io\streams\{InputStream, StringReader}; -/** @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource */ +/** + * Event source is the receiving end for server-sent events, handling the + * `text/event-stream` wire format. + * + * @test web.unittest.io.EventSourceTest + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource + */ class EventSource implements IteratorAggregate { private $reader; @@ -15,7 +21,7 @@ public function __construct(InputStream $in) { /** Yields events and associated data */ public function getIterator(): Traversable { $event= null; - while ($line= $this->reader->readLine()) { + while (null !== ($line= $this->reader->readLine())) { if (0 === strncmp($line, 'event: ', 7)) { $event= substr($line, 7); } else if (0 === strncmp($line, 'data: ', 6)) { diff --git a/src/test/php/web/unittest/io/EventSourceTest.class.php b/src/test/php/web/unittest/io/EventSourceTest.class.php new file mode 100755 index 0000000..ceb8a50 --- /dev/null +++ b/src/test/php/web/unittest/io/EventSourceTest.class.php @@ -0,0 +1,39 @@ + 'One']]]; + yield [['', 'data: One'], [[null => 'One']]]; + yield [['data: One', '', 'data: Two'], [[null => 'One'], [null => 'Two']]]; + yield [['event: test', 'data: One'], [['test' => 'One']]]; + yield [['event: test', 'data: One', '', 'data: Two'], [['test' => 'One'], [null => 'Two']]]; + } + + #[Test] + public function can_create() { + new EventSource($this->stream([])); + } + + #[Test, Values(from: 'inputs')] + public function events($lines, $expected) { + $events= new EventSource($this->stream($lines)); + $actual= []; + foreach ($events as $type => $event) { + $actual[]= [$type => $event]; + } + Assert::equals($expected, $actual); + } +} \ No newline at end of file