Skip to content

Commit

Permalink
Add test for EventSource implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
thekid committed Jan 18, 2025
1 parent d013905 commit db560b2
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
10 changes: 8 additions & 2 deletions src/main/php/web/io/EventSource.class.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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)) {
Expand Down
39 changes: 39 additions & 0 deletions src/test/php/web/unittest/io/EventSourceTest.class.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php namespace web\unittest\io;

use io\streams\{InputStream, MemoryInputStream};
use test\{Assert, Test, Values};
use web\io\EventSource;

class EventSourceTest {

/** Returns an input stream from the given lines */
private function stream(array $lines): InputStream {
return new MemoryInputStream(implode("\n", $lines));
}

/** @return iterable */
private function inputs() {
yield [[], []];
yield [[''], []];
yield [['data: One'], [[null => '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);
}
}

0 comments on commit db560b2

Please sign in to comment.