Merge pull request #61 from mbabker/phpunit-upgrade

[0.4] Use latest PHPUnit and modernize test code
This commit is contained in:
Chris Boden 2021-12-12 14:25:53 -05:00 committed by GitHub
commit 5d67378e09
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 190 additions and 256 deletions

View File

@ -15,6 +15,8 @@ jobs:
- server - server
php: php:
- 7.4 - 7.4
- 8.0
- 8.1
steps: steps:
- uses: actions/checkout@v2 - uses: actions/checkout@v2
- name: Setup PHP - name: Setup PHP

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
.phpunit.result.cache
composer.lock composer.lock
vendor vendor
tests/ab/reports tests/ab/reports

View File

@ -30,7 +30,7 @@
"guzzlehttp/psr7": "^2 || ^1.7" "guzzlehttp/psr7": "^2 || ^1.7"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^5.7", "phpunit/phpunit": "^9.5",
"react/socket": "^1.3" "react/socket": "^1.3"
}, },
"scripts": { "scripts": {

View File

@ -1,27 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<phpunit <phpunit
forceCoversAnnotation="true" forceCoversAnnotation="true"
mapTestClassNameToCoveredClassName="true"
bootstrap="tests/bootstrap.php" bootstrap="tests/bootstrap.php"
colors="true" colors="true"
backupGlobals="false" backupGlobals="false"
backupStaticAttributes="false" backupStaticAttributes="false"
syntaxCheck="false"
stopOnError="false" stopOnError="false"
> >
<testsuites> <testsuites>
<testsuite name="tests"> <testsuite name="tests">
<directory>tests</directory> <directory>./tests</directory>
<exclude>
<directory>test/ab</directory>
</exclude>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter> <coverage processUncoveredFiles="true">
<whitelist> <include>
<directory>./src/</directory> <directory suffix=".php">./src</directory>
</whitelist> </include>
</filter> </coverage>
</phpunit> </phpunit>

View File

@ -3,10 +3,13 @@
namespace Ratchet\RFC6455\Test; namespace Ratchet\RFC6455\Test;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/**
* @coversNothing
*/
class AbResultsTest extends TestCase { class AbResultsTest extends TestCase {
private function verifyAutobahnResults($fileName) { private function verifyAutobahnResults(string $fileName): void {
if (!file_exists($fileName)) { if (!file_exists($fileName)) {
return $this->markTestSkipped('Autobahn TestSuite results not found'); $this->markTestSkipped('Autobahn TestSuite results not found');
} }
$resultsJson = file_get_contents($fileName); $resultsJson = file_get_contents($fileName);
@ -22,11 +25,11 @@ class AbResultsTest extends TestCase {
} }
} }
public function testAutobahnClientResults() { public function testAutobahnClientResults(): void {
$this->verifyAutobahnResults(__DIR__ . '/ab/reports/clients/index.json'); $this->verifyAutobahnResults(__DIR__ . '/ab/reports/clients/index.json');
} }
public function testAutobahnServerResults() { public function testAutobahnServerResults(): void {
$this->verifyAutobahnResults(__DIR__ . '/ab/reports/servers/index.json'); $this->verifyAutobahnResults(__DIR__ . '/ab/reports/servers/index.json');
} }
} }

View File

@ -4,12 +4,14 @@ use GuzzleHttp\Psr7\Message;
use GuzzleHttp\Psr7\Uri; use GuzzleHttp\Psr7\Uri;
use Ratchet\RFC6455\Handshake\InvalidPermessageDeflateOptionsException; use Ratchet\RFC6455\Handshake\InvalidPermessageDeflateOptionsException;
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions; use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
use Ratchet\RFC6455\Messaging\FrameInterface;
use Ratchet\RFC6455\Messaging\MessageBuffer; use Ratchet\RFC6455\Messaging\MessageBuffer;
use Ratchet\RFC6455\Handshake\ClientNegotiator; use Ratchet\RFC6455\Handshake\ClientNegotiator;
use Ratchet\RFC6455\Messaging\CloseFrameChecker; use Ratchet\RFC6455\Messaging\CloseFrameChecker;
use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\RFC6455\Messaging\MessageInterface;
use React\Promise\Deferred; use React\Promise\Deferred;
use Ratchet\RFC6455\Messaging\Frame; use Ratchet\RFC6455\Messaging\Frame;
use React\Promise\PromiseInterface;
use React\Socket\ConnectionInterface; use React\Socket\ConnectionInterface;
use React\Socket\Connector; use React\Socket\Connector;
@ -23,23 +25,21 @@ $loop = React\EventLoop\Factory::create();
$connector = new Connector($loop); $connector = new Connector($loop);
function echoStreamerFactory($conn, $permessageDeflateOptions = null) function echoStreamerFactory(ConnectionInterface $conn, ?PermessageDeflateOptions $permessageDeflateOptions = null): MessageBuffer
{ {
$permessageDeflateOptions = $permessageDeflateOptions ?: PermessageDeflateOptions::createDisabled(); $permessageDeflateOptions = $permessageDeflateOptions ?: PermessageDeflateOptions::createDisabled();
return new \Ratchet\RFC6455\Messaging\MessageBuffer( return new MessageBuffer(
new \Ratchet\RFC6455\Messaging\CloseFrameChecker, new CloseFrameChecker,
function (\Ratchet\RFC6455\Messaging\MessageInterface $msg, MessageBuffer $messageBuffer) use ($conn) { static function (MessageInterface $msg, MessageBuffer $messageBuffer) use ($conn): void {
$messageBuffer->sendMessage($msg->getPayload(), true, $msg->isBinary()); $messageBuffer->sendMessage($msg->getPayload(), true, $msg->isBinary());
}, },
function (\Ratchet\RFC6455\Messaging\FrameInterface $frame, MessageBuffer $messageBuffer) use ($conn) { static function (FrameInterface $frame, MessageBuffer $messageBuffer) use ($conn) {
switch ($frame->getOpcode()) { switch ($frame->getOpcode()) {
case Frame::OP_PING: case Frame::OP_PING:
return $conn->write((new Frame($frame->getPayload(), true, Frame::OP_PONG))->maskPayload()->getContents()); return $conn->write((new Frame($frame->getPayload(), true, Frame::OP_PONG))->maskPayload()->getContents());
break;
case Frame::OP_CLOSE: case Frame::OP_CLOSE:
return $conn->end((new Frame($frame->getPayload(), true, Frame::OP_CLOSE))->maskPayload()->getContents()); return $conn->end((new Frame($frame->getPayload(), true, Frame::OP_CLOSE))->maskPayload()->getContents());
break;
} }
}, },
false, false,
@ -51,13 +51,13 @@ function echoStreamerFactory($conn, $permessageDeflateOptions = null)
); );
} }
function getTestCases() { function getTestCases(): PromiseInterface {
global $testServer; global $testServer;
global $connector; global $connector;
$deferred = new Deferred(); $deferred = new Deferred();
$connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $testServer) { $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $testServer): void {
$cn = new ClientNegotiator(); $cn = new ClientNegotiator();
$cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002/getCaseCount')); $cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002/getCaseCount'));
@ -67,7 +67,7 @@ function getTestCases() {
/** @var MessageBuffer $ms */ /** @var MessageBuffer $ms */
$ms = null; $ms = null;
$connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) { $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) { if ($response === null) {
$rawResponse .= $data; $rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n"); $pos = strpos($rawResponse, "\r\n\r\n");
@ -82,7 +82,7 @@ function getTestCases() {
} else { } else {
$ms = new MessageBuffer( $ms = new MessageBuffer(
new CloseFrameChecker, new CloseFrameChecker,
function (MessageInterface $msg) use ($deferred, $connection) { static function (MessageInterface $msg) use ($deferred, $connection): void {
$deferred->resolve($msg->getPayload()); $deferred->resolve($msg->getPayload());
$connection->close(); $connection->close();
}, },
@ -91,7 +91,7 @@ function getTestCases() {
null, null,
null, null,
null, null,
function () {} static function (): void {}
); );
} }
} }
@ -109,10 +109,10 @@ function getTestCases() {
return $deferred->promise(); return $deferred->promise();
} }
$cn = new \Ratchet\RFC6455\Handshake\ClientNegotiator( $cn = new ClientNegotiator(
PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null); PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null);
function runTest($case) function runTest(int $case)
{ {
global $connector; global $connector;
global $testServer; global $testServer;
@ -122,7 +122,7 @@ function runTest($case)
$deferred = new Deferred(); $deferred = new Deferred();
$connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $casePath, $case, $testServer) { $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $casePath, $case, $testServer): void {
$cn = new ClientNegotiator( $cn = new ClientNegotiator(
PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null); PermessageDeflateOptions::permessageDeflateSupported() ? PermessageDeflateOptions::createEnabled() : null);
$cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002' . $casePath)); $cnRequest = $cn->generateRequest(new Uri('ws://' . $testServer . ':9002' . $casePath));
@ -132,7 +132,7 @@ function runTest($case)
$ms = null; $ms = null;
$connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) { $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) { if ($response === null) {
$rawResponse .= $data; $rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n"); $pos = strpos($rawResponse, "\r\n\r\n");
@ -165,7 +165,7 @@ function runTest($case)
} }
}); });
$connection->on('close', function () use ($deferred) { $connection->on('close', static function () use ($deferred): void {
$deferred->resolve(); $deferred->resolve();
}); });
@ -175,13 +175,13 @@ function runTest($case)
return $deferred->promise(); return $deferred->promise();
} }
function createReport() { function createReport(): PromiseInterface {
global $connector; global $connector;
global $testServer; global $testServer;
$deferred = new Deferred(); $deferred = new Deferred();
$connector->connect($testServer . ':9002')->then(function (ConnectionInterface $connection) use ($deferred, $testServer) { $connector->connect($testServer . ':9002')->then(static function (ConnectionInterface $connection) use ($deferred, $testServer): void {
// $reportPath = "/updateReports?agent=" . AGENT . "&shutdownOnComplete=true"; // $reportPath = "/updateReports?agent=" . AGENT . "&shutdownOnComplete=true";
// we will stop it using docker now instead of just shutting down // we will stop it using docker now instead of just shutting down
$reportPath = "/updateReports?agent=" . AGENT; $reportPath = "/updateReports?agent=" . AGENT;
@ -194,7 +194,7 @@ function createReport() {
/** @var MessageBuffer $ms */ /** @var MessageBuffer $ms */
$ms = null; $ms = null;
$connection->on('data', function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest) { $connection->on('data', static function ($data) use ($connection, &$rawResponse, &$response, &$ms, $cn, $deferred, &$context, $cnRequest): void {
if ($response === null) { if ($response === null) {
$rawResponse .= $data; $rawResponse .= $data;
$pos = strpos($rawResponse, "\r\n\r\n"); $pos = strpos($rawResponse, "\r\n\r\n");
@ -209,7 +209,7 @@ function createReport() {
} else { } else {
$ms = new MessageBuffer( $ms = new MessageBuffer(
new CloseFrameChecker, new CloseFrameChecker,
function (MessageInterface $msg) use ($deferred, $connection) { static function (MessageInterface $msg) use ($deferred, $connection): void {
$deferred->resolve($msg->getPayload()); $deferred->resolve($msg->getPayload());
$connection->close(); $connection->close();
}, },
@ -218,7 +218,7 @@ function createReport() {
null, null,
null, null,
null, null,
function () {} static function (): void {}
); );
} }
} }
@ -242,7 +242,7 @@ $testPromises = [];
getTestCases()->then(function ($count) use ($loop) { getTestCases()->then(function ($count) use ($loop) {
$allDeferred = new Deferred(); $allDeferred = new Deferred();
$runNextCase = function () use (&$i, &$runNextCase, $count, $allDeferred) { $runNextCase = static function () use (&$i, &$runNextCase, $count, $allDeferred): void {
$i++; $i++;
if ($i > $count) { if ($i > $count) {
$allDeferred->resolve(); $allDeferred->resolve();
@ -251,7 +251,7 @@ getTestCases()->then(function ($count) use ($loop) {
echo "Running test $i/$count..."; echo "Running test $i/$count...";
$startTime = microtime(true); $startTime = microtime(true);
runTest($i) runTest($i)
->then(function () use ($startTime) { ->then(static function () use ($startTime): void {
echo " completed " . round((microtime(true) - $startTime) * 1000) . " ms\n"; echo " completed " . round((microtime(true) - $startTime) * 1000) . " ms\n";
}) })
->then($runNextCase); ->then($runNextCase);
@ -260,7 +260,7 @@ getTestCases()->then(function ($count) use ($loop) {
$i = 0; $i = 0;
$runNextCase(); $runNextCase();
$allDeferred->promise()->then(function () { $allDeferred->promise()->then(static function (): void {
createReport(); createReport();
}); });
}); });

View File

@ -3,6 +3,9 @@
use GuzzleHttp\Psr7\Message; use GuzzleHttp\Psr7\Message;
use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Response;
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions; use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
use Ratchet\RFC6455\Handshake\RequestVerifier;
use Ratchet\RFC6455\Handshake\ServerNegotiator;
use Ratchet\RFC6455\Messaging\CloseFrameChecker;
use Ratchet\RFC6455\Messaging\MessageBuffer; use Ratchet\RFC6455\Messaging\MessageBuffer;
use Ratchet\RFC6455\Messaging\MessageInterface; use Ratchet\RFC6455\Messaging\MessageInterface;
use Ratchet\RFC6455\Messaging\FrameInterface; use Ratchet\RFC6455\Messaging\FrameInterface;
@ -14,17 +17,17 @@ $loop = \React\EventLoop\Factory::create();
$socket = new \React\Socket\Server('0.0.0.0:9001', $loop); $socket = new \React\Socket\Server('0.0.0.0:9001', $loop);
$closeFrameChecker = new \Ratchet\RFC6455\Messaging\CloseFrameChecker; $closeFrameChecker = new CloseFrameChecker;
$negotiator = new \Ratchet\RFC6455\Handshake\ServerNegotiator(new \Ratchet\RFC6455\Handshake\RequestVerifier, PermessageDeflateOptions::permessageDeflateSupported()); $negotiator = new ServerNegotiator(new RequestVerifier, PermessageDeflateOptions::permessageDeflateSupported());
$uException = new \UnderflowException; $uException = new \UnderflowException;
$socket->on('connection', function (React\Socket\ConnectionInterface $connection) use ($negotiator, $closeFrameChecker, $uException, $socket) { $socket->on('connection', static function (React\Socket\ConnectionInterface $connection) use ($negotiator, $closeFrameChecker, $uException, $socket): void {
$headerComplete = false; $headerComplete = false;
$buffer = ''; $buffer = '';
$parser = null; $parser = null;
$connection->on('data', function ($data) use ($connection, &$parser, &$headerComplete, &$buffer, $negotiator, $closeFrameChecker, $uException, $socket) { $connection->on('data', static function ($data) use ($connection, &$parser, &$headerComplete, &$buffer, $negotiator, $closeFrameChecker, $uException, $socket): void {
if ($headerComplete) { if ($headerComplete) {
$parser->onData($data); $parser->onData($data);
return; return;
@ -58,10 +61,10 @@ $socket->on('connection', function (React\Socket\ConnectionInterface $connection
// we support any valid permessage deflate // we support any valid permessage deflate
$deflateOptions = PermessageDeflateOptions::fromRequestOrResponse($psrRequest)[0]; $deflateOptions = PermessageDeflateOptions::fromRequestOrResponse($psrRequest)[0];
$parser = new \Ratchet\RFC6455\Messaging\MessageBuffer($closeFrameChecker, $parser = new MessageBuffer($closeFrameChecker,
function (MessageInterface $message, MessageBuffer $messageBuffer) { static function (MessageInterface $message, MessageBuffer $messageBuffer): void {
$messageBuffer->sendMessage($message->getPayload(), true, $message->isBinary()); $messageBuffer->sendMessage($message->getPayload(), true, $message->isBinary());
}, function (FrameInterface $frame) use ($connection, &$parser) { }, static function (FrameInterface $frame) use ($connection, &$parser): void {
switch ($frame->getOpCode()) { switch ($frame->getOpCode()) {
case Frame::OP_CLOSE: case Frame::OP_CLOSE:
$connection->end($frame->getContents()); $connection->end($frame->getContents());
@ -70,9 +73,7 @@ $socket->on('connection', function (React\Socket\ConnectionInterface $connection
$connection->write($parser->newFrame($frame->getPayload(), true, Frame::OP_PONG)->getContents()); $connection->write($parser->newFrame($frame->getPayload(), true, Frame::OP_PONG)->getContents());
break; break;
} }
}, true, function () use ($uException) { }, true, static fn (): \Exception => $uException,
return $uException;
},
null, null,
null, null,
[$connection, 'write'], [$connection, 'write'],

View File

@ -5,9 +5,12 @@ namespace Ratchet\RFC6455\Test\Unit\Handshake;
use Ratchet\RFC6455\Handshake\PermessageDeflateOptions; use Ratchet\RFC6455\Handshake\PermessageDeflateOptions;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/**
* @covers Ratchet\RFC6455\Handshake\PermessageDeflateOptions
*/
class PermessageDeflateOptionsTest extends TestCase class PermessageDeflateOptionsTest extends TestCase
{ {
public static function versionSupportProvider() { public static function versionSupportProvider(): array {
return [ return [
['7.0.17', false], ['7.0.17', false],
['7.0.18', true], ['7.0.18', true],
@ -24,7 +27,7 @@ class PermessageDeflateOptionsTest extends TestCase
* @requires function deflate_init * @requires function deflate_init
* @dataProvider versionSupportProvider * @dataProvider versionSupportProvider
*/ */
public function testVersionSupport($version, $supported) { public function testVersionSupport(string $version, bool $supported): void {
$this->assertEquals($supported, PermessageDeflateOptions::permessageDeflateSupported($version)); $this->assertEquals($supported, PermessageDeflateOptions::permessageDeflateSupported($version));
} }
} }

View File

@ -14,11 +14,11 @@ class RequestVerifierTest extends TestCase {
*/ */
protected $_v; protected $_v;
public function setUp() { protected function setUp(): void {
$this->_v = new RequestVerifier(); $this->_v = new RequestVerifier();
} }
public static function methodProvider() { public static function methodProvider(): array {
return array( return array(
array(true, 'GET'), array(true, 'GET'),
array(true, 'get'), array(true, 'get'),
@ -32,11 +32,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider methodProvider * @dataProvider methodProvider
*/ */
public function testMethodMustBeGet($result, $in) { public function testMethodMustBeGet(bool $result, string $in): void {
$this->assertEquals($result, $this->_v->verifyMethod($in)); $this->assertEquals($result, $this->_v->verifyMethod($in));
} }
public static function httpVersionProvider() { public static function httpVersionProvider(): array {
return array( return array(
array(true, 1.1), array(true, 1.1),
array(true, '1.1'), array(true, '1.1'),
@ -56,11 +56,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider httpVersionProvider * @dataProvider httpVersionProvider
*/ */
public function testHttpVersionIsAtLeast1Point1($expected, $in) { public function testHttpVersionIsAtLeast1Point1(bool $expected, $in): void {
$this->assertEquals($expected, $this->_v->verifyHTTPVersion($in)); $this->assertEquals($expected, $this->_v->verifyHTTPVersion($in));
} }
public static function uRIProvider() { public static function uRIProvider(): array {
return array( return array(
array(true, '/chat'), array(true, '/chat'),
array(true, '/hello/world?key=val'), array(true, '/hello/world?key=val'),
@ -74,11 +74,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider URIProvider * @dataProvider URIProvider
*/ */
public function testRequestUri($expected, $in) { public function testRequestUri(bool $expected, string $in): void {
$this->assertEquals($expected, $this->_v->verifyRequestURI($in)); $this->assertEquals($expected, $this->_v->verifyRequestURI($in));
} }
public static function hostProvider() { public static function hostProvider(): array {
return array( return array(
array(true, ['server.example.com']), array(true, ['server.example.com']),
array(false, []) array(false, [])
@ -88,11 +88,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider HostProvider * @dataProvider HostProvider
*/ */
public function testVerifyHostIsSet($expected, $in) { public function testVerifyHostIsSet(bool $expected, array $in): void {
$this->assertEquals($expected, $this->_v->verifyHost($in)); $this->assertEquals($expected, $this->_v->verifyHost($in));
} }
public static function upgradeProvider() { public static function upgradeProvider(): array {
return array( return array(
array(true, ['websocket']), array(true, ['websocket']),
array(true, ['Websocket']), array(true, ['Websocket']),
@ -105,11 +105,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider upgradeProvider * @dataProvider upgradeProvider
*/ */
public function testVerifyUpgradeIsWebSocket($expected, $val) { public function testVerifyUpgradeIsWebSocket(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyUpgradeRequest($val)); $this->assertEquals($expected, $this->_v->verifyUpgradeRequest($val));
} }
public static function connectionProvider() { public static function connectionProvider(): array {
return array( return array(
array(true, ['Upgrade']), array(true, ['Upgrade']),
array(true, ['upgrade']), array(true, ['upgrade']),
@ -129,11 +129,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider connectionProvider * @dataProvider connectionProvider
*/ */
public function testConnectionHeaderVerification($expected, $val) { public function testConnectionHeaderVerification(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyConnection($val)); $this->assertEquals($expected, $this->_v->verifyConnection($val));
} }
public static function keyProvider() { public static function keyProvider(): array {
return array( return array(
array(true, ['hkfa1L7uwN6DCo4IS3iWAw==']), array(true, ['hkfa1L7uwN6DCo4IS3iWAw==']),
array(true, ['765vVoQpKSGJwPzJIMM2GA==']), array(true, ['765vVoQpKSGJwPzJIMM2GA==']),
@ -154,11 +154,11 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider keyProvider * @dataProvider keyProvider
*/ */
public function testKeyIsBase64Encoded16BitNonce($expected, $val) { public function testKeyIsBase64Encoded16BitNonce(bool $expected, array $val): void {
$this->assertEquals($expected, $this->_v->verifyKey($val)); $this->assertEquals($expected, $this->_v->verifyKey($val));
} }
public static function versionProvider() { public static function versionProvider(): array {
return array( return array(
array(true, [13]), array(true, [13]),
array(true, ['13']), array(true, ['13']),
@ -174,7 +174,7 @@ class RequestVerifierTest extends TestCase {
/** /**
* @dataProvider versionProvider * @dataProvider versionProvider
*/ */
public function testVersionEquals13($expected, $in) { public function testVersionEquals13(bool $expected, array $in): void {
$this->assertEquals($expected, $this->_v->verifyVersion($in)); $this->assertEquals($expected, $this->_v->verifyVersion($in));
} }
} }

View File

@ -14,11 +14,11 @@ class ResponseVerifierTest extends TestCase {
*/ */
protected $_v; protected $_v;
public function setUp() { protected function setUp(): void {
$this->_v = new ResponseVerifier; $this->_v = new ResponseVerifier;
} }
public static function subProtocolsProvider() { public static function subProtocolsProvider(): array {
return [ return [
[true, ['a'], ['a']] [true, ['a'], ['a']]
, [true, ['c', 'd', 'a'], ['a']] , [true, ['c', 'd', 'a'], ['a']]
@ -33,7 +33,7 @@ class ResponseVerifierTest extends TestCase {
/** /**
* @dataProvider subProtocolsProvider * @dataProvider subProtocolsProvider
*/ */
public function testVerifySubProtocol($expected, $request, $response) { public function testVerifySubProtocol(bool $expected, array $request, array $response): void {
$this->assertEquals($expected, $this->_v->verifySubProtocol($request, $response)); $this->assertEquals($expected, $this->_v->verifySubProtocol($request, $response));
} }
} }

View File

@ -7,9 +7,12 @@ use Ratchet\RFC6455\Handshake\RequestVerifier;
use Ratchet\RFC6455\Handshake\ServerNegotiator; use Ratchet\RFC6455\Handshake\ServerNegotiator;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/**
* @covers Ratchet\RFC6455\Handshake\ServerNegotiator
*/
class ServerNegotiatorTest extends TestCase class ServerNegotiatorTest extends TestCase
{ {
public function testNoUpgradeRequested() { public function testNoUpgradeRequested(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$requestText = 'GET / HTTP/1.1 $requestText = 'GET / HTTP/1.1
@ -37,7 +40,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
} }
public function testNoConnectionUpgradeRequested() { public function testNoConnectionUpgradeRequested(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$requestText = 'GET / HTTP/1.1 $requestText = 'GET / HTTP/1.1
@ -63,7 +66,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertEquals('Connection Upgrade MUST be requested', $response->getReasonPhrase()); $this->assertEquals('Connection Upgrade MUST be requested', $response->getReasonPhrase());
} }
public function testInvalidSecWebsocketKey() { public function testInvalidSecWebsocketKey(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$requestText = 'GET / HTTP/1.1 $requestText = 'GET / HTTP/1.1
@ -90,7 +93,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertEquals('Invalid Sec-WebSocket-Key', $response->getReasonPhrase()); $this->assertEquals('Invalid Sec-WebSocket-Key', $response->getReasonPhrase());
} }
public function testInvalidSecWebsocketVersion() { public function testInvalidSecWebsocketVersion(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$requestText = 'GET / HTTP/1.1 $requestText = 'GET / HTTP/1.1
@ -120,7 +123,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
} }
public function testBadSubprotocolResponse() { public function testBadSubprotocolResponse(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$negotiator->setStrictSubProtocolCheck(true); $negotiator->setStrictSubProtocolCheck(true);
$negotiator->setSupportedSubProtocols([]); $negotiator->setSupportedSubProtocols([]);
@ -154,7 +157,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version')); $this->assertEquals('13', $response->getHeaderLine('Sec-WebSocket-Version'));
} }
public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn() { public function testNonStrictSubprotocolDoesNotIncludeHeaderWhenNoneAgreedOn(): void {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$negotiator->setStrictSubProtocolCheck(false); $negotiator->setStrictSubProtocolCheck(false);
$negotiator->setSupportedSubProtocols(['someproto']); $negotiator->setSupportedSubProtocols(['someproto']);
@ -187,7 +190,7 @@ Accept-Language: en-US,en;q=0.8
$this->assertFalse($response->hasHeader('Sec-WebSocket-Protocol')); $this->assertFalse($response->hasHeader('Sec-WebSocket-Protocol'));
} }
public function testSuggestsAppropriateSubprotocol() public function testSuggestsAppropriateSubprotocol(): void
{ {
$negotiator = new ServerNegotiator(new RequestVerifier()); $negotiator = new ServerNegotiator(new RequestVerifier());
$negotiator->setStrictSubProtocolCheck(true); $negotiator->setStrictSubProtocolCheck(true);

View File

@ -20,7 +20,7 @@ class FrameTest extends TestCase {
protected $_packer; protected $_packer;
public function setUp() { protected function setUp(): void {
$this->_frame = new Frame; $this->_frame = new Frame;
} }
@ -29,7 +29,7 @@ class FrameTest extends TestCase {
* @param string of 1's and 0's * @param string of 1's and 0's
* @return string * @return string
*/ */
public static function encode($in) { public static function encode(string $in): string {
if (strlen($in) > 8) { if (strlen($in) > 8) {
$out = ''; $out = '';
while (strlen($in) >= 8) { while (strlen($in) >= 8) {
@ -46,7 +46,7 @@ class FrameTest extends TestCase {
* param string The UTF8 message * param string The UTF8 message
* param string The WebSocket framed message, then base64_encoded * param string The WebSocket framed message, then base64_encoded
*/ */
public static function UnframeMessageProvider() { public static function UnframeMessageProvider(): array {
return array( return array(
array('Hello World!', 'gYydAIfa1WXrtvIg0LXvbOP7'), array('Hello World!', 'gYydAIfa1WXrtvIg0LXvbOP7'),
array('!@#$%^&*()-=_+[]{}\|/.,<>`~', 'gZv+h96r38f9j9vZ+IHWrvOWoayF9oX6gtfRqfKXwOeg'), array('!@#$%^&*()-=_+[]{}\|/.,<>`~', 'gZv+h96r38f9j9vZ+IHWrvOWoayF9oX6gtfRqfKXwOeg'),
@ -58,7 +58,7 @@ class FrameTest extends TestCase {
); );
} }
public static function underflowProvider() { public static function underflowProvider(): array {
return array( return array(
array('isFinal', ''), array('isFinal', ''),
array('getRsv1', ''), array('getRsv1', ''),
@ -75,19 +75,9 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider underflowProvider * @dataProvider underflowProvider
*
* @covers Ratchet\RFC6455\Messaging\Frame::isFinal
* @covers Ratchet\RFC6455\Messaging\Frame::getRsv1
* @covers Ratchet\RFC6455\Messaging\Frame::getRsv2
* @covers Ratchet\RFC6455\Messaging\Frame::getRsv3
* @covers Ratchet\RFC6455\Messaging\Frame::getOpcode
* @covers Ratchet\RFC6455\Messaging\Frame::isMasked
* @covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
* @covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
* @covers Ratchet\RFC6455\Messaging\Frame::getPayload
*/ */
public function testUnderflowExceptionFromAllTheMethodsMimickingBuffering($method, $bin) { public function testUnderflowExceptionFromAllTheMethodsMimickingBuffering(string $method, string $bin): void {
$this->setExpectedException('\UnderflowException'); $this->expectException(\UnderflowException::class);
if (!empty($bin)) { if (!empty($bin)) {
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
} }
@ -100,7 +90,7 @@ class FrameTest extends TestCase {
* param int Given, what is the expected opcode * param int Given, what is the expected opcode
* param string of 0|1 Each character represents a bit in the byte * param string of 0|1 Each character represents a bit in the byte
*/ */
public static function firstByteProvider() { public static function firstByteProvider(): array {
return array( return array(
array(false, false, false, true, 8, '00011000'), array(false, false, false, true, 8, '00011000'),
array(true, false, true, false, 10, '10101010'), array(true, false, true, false, 10, '10101010'),
@ -113,20 +103,16 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider firstByteProvider * @dataProvider firstByteProvider
* covers Ratchet\RFC6455\Messaging\Frame::isFinal
*/ */
public function testFinCodeFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) { public function testFinCodeFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($fin, $this->_frame->isFinal()); $this->assertEquals($fin, $this->_frame->isFinal());
} }
/** /**
* @dataProvider firstByteProvider * @dataProvider firstByteProvider
* covers Ratchet\RFC6455\Messaging\Frame::getRsv1
* covers Ratchet\RFC6455\Messaging\Frame::getRsv2
* covers Ratchet\RFC6455\Messaging\Frame::getRsv3
*/ */
public function testGetRsvFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) { public function testGetRsvFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($rsv1, $this->_frame->getRsv1()); $this->assertEquals($rsv1, $this->_frame->getRsv1());
$this->assertEquals($rsv2, $this->_frame->getRsv2()); $this->assertEquals($rsv2, $this->_frame->getRsv2());
@ -135,32 +121,29 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider firstByteProvider * @dataProvider firstByteProvider
* covers Ratchet\RFC6455\Messaging\Frame::getOpcode
*/ */
public function testOpcodeFromBits($fin, $rsv1, $rsv2, $rsv3, $opcode, $bin) { public function testOpcodeFromBits(bool $fin, bool $rsv1, bool $rsv2, bool $rsv3, int $opcode, string $bin): void {
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($opcode, $this->_frame->getOpcode()); $this->assertEquals($opcode, $this->_frame->getOpcode());
} }
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::isFinal
*/ */
public function testFinCodeFromFullMessage($msg, $encoded) { public function testFinCodeFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded)); $this->_frame->addBuffer(base64_decode($encoded));
$this->assertTrue($this->_frame->isFinal()); $this->assertTrue($this->_frame->isFinal());
} }
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::getOpcode
*/ */
public function testOpcodeFromFullMessage($msg, $encoded) { public function testOpcodeFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded)); $this->_frame->addBuffer(base64_decode($encoded));
$this->assertEquals(1, $this->_frame->getOpcode()); $this->assertEquals(1, $this->_frame->getOpcode());
} }
public static function payloadLengthDescriptionProvider() { public static function payloadLengthDescriptionProvider(): array {
return array( return array(
array(7, '01110101'), array(7, '01110101'),
array(7, '01111101'), array(7, '01111101'),
@ -173,10 +156,8 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider payloadLengthDescriptionProvider * @dataProvider payloadLengthDescriptionProvider
* covers Ratchet\RFC6455\Messaging\Frame::addBuffer
* covers Ratchet\RFC6455\Messaging\Frame::getFirstPayloadVal
*/ */
public function testFirstPayloadDesignationValue($bits, $bin) { public function testFirstPayloadDesignationValue(int $bits, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText)); $this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$ref = new \ReflectionClass($this->_frame); $ref = new \ReflectionClass($this->_frame);
@ -185,22 +166,18 @@ class FrameTest extends TestCase {
$this->assertEquals(bindec($bin), $cb->invoke($this->_frame)); $this->assertEquals(bindec($bin), $cb->invoke($this->_frame));
} }
/** public function testFirstPayloadValUnderflow(): void {
* covers Ratchet\RFC6455\Messaging\Frame::getFirstPayloadVal
*/
public function testFirstPayloadValUnderflow() {
$ref = new \ReflectionClass($this->_frame); $ref = new \ReflectionClass($this->_frame);
$cb = $ref->getMethod('getFirstPayloadVal'); $cb = $ref->getMethod('getFirstPayloadVal');
$cb->setAccessible(true); $cb->setAccessible(true);
$this->setExpectedException('UnderflowException'); $this->expectException(\UnderflowException::class);
$cb->invoke($this->_frame); $cb->invoke($this->_frame);
} }
/** /**
* @dataProvider payloadLengthDescriptionProvider * @dataProvider payloadLengthDescriptionProvider
* covers Ratchet\RFC6455\Messaging\Frame::getNumPayloadBits
*/ */
public function testDetermineHowManyBitsAreUsedToDescribePayload($expected_bits, $bin) { public function testDetermineHowManyBitsAreUsedToDescribePayload(int $expected_bits, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText)); $this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$ref = new \ReflectionClass($this->_frame); $ref = new \ReflectionClass($this->_frame);
@ -209,18 +186,15 @@ class FrameTest extends TestCase {
$this->assertEquals($expected_bits, $cb->invoke($this->_frame)); $this->assertEquals($expected_bits, $cb->invoke($this->_frame));
} }
/** public function testgetNumPayloadBitsUnderflow(): void {
* covers Ratchet\RFC6455\Messaging\Frame::getNumPayloadBits
*/
public function testgetNumPayloadBitsUnderflow() {
$ref = new \ReflectionClass($this->_frame); $ref = new \ReflectionClass($this->_frame);
$cb = $ref->getMethod('getNumPayloadBits'); $cb = $ref->getMethod('getNumPayloadBits');
$cb->setAccessible(true); $cb->setAccessible(true);
$this->setExpectedException('UnderflowException'); $this->expectException(\UnderflowException::class);
$cb->invoke($this->_frame); $cb->invoke($this->_frame);
} }
public function secondByteProvider() { public function secondByteProvider(): array {
return array( return array(
array(true, 1, '10000001'), array(true, 1, '10000001'),
array(false, 1, '00000001'), array(false, 1, '00000001'),
@ -229,9 +203,8 @@ class FrameTest extends TestCase {
} }
/** /**
* @dataProvider secondByteProvider * @dataProvider secondByteProvider
* covers Ratchet\RFC6455\Messaging\Frame::isMasked
*/ */
public function testIsMaskedReturnsExpectedValue($masked, $payload_length, $bin) { public function testIsMaskedReturnsExpectedValue(bool $masked, int $payload_length, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText)); $this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($masked, $this->_frame->isMasked()); $this->assertEquals($masked, $this->_frame->isMasked());
@ -239,18 +212,16 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::isMasked
*/ */
public function testIsMaskedFromFullMessage($msg, $encoded) { public function testIsMaskedFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded)); $this->_frame->addBuffer(base64_decode($encoded));
$this->assertTrue($this->_frame->isMasked()); $this->assertTrue($this->_frame->isMasked());
} }
/** /**
* @dataProvider secondByteProvider * @dataProvider secondByteProvider
* covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
*/ */
public function testGetPayloadLengthWhenOnlyFirstFrameIsUsed($masked, $payload_length, $bin) { public function testGetPayloadLengthWhenOnlyFirstFrameIsUsed(bool $masked, int $payload_length, string $bin): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText)); $this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($bin)); $this->_frame->addBuffer(static::encode($bin));
$this->assertEquals($payload_length, $this->_frame->getPayloadLength()); $this->assertEquals($payload_length, $this->_frame->getPayloadLength());
@ -258,15 +229,14 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
* @todo Not yet testing when second additional payload length descriptor * @todo Not yet testing when second additional payload length descriptor
*/ */
public function testGetPayloadLengthFromFullMessage($msg, $encoded) { public function testGetPayloadLengthFromFullMessage(string $msg, string $encoded): void {
$this->_frame->addBuffer(base64_decode($encoded)); $this->_frame->addBuffer(base64_decode($encoded));
$this->assertEquals(strlen($msg), $this->_frame->getPayloadLength()); $this->assertEquals(strlen($msg), $this->_frame->getPayloadLength());
} }
public function maskingKeyProvider() { public function maskingKeyProvider(): array {
$frame = new Frame; $frame = new Frame;
return array( return array(
array($frame->generateMaskingKey()), array($frame->generateMaskingKey()),
@ -277,35 +247,30 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider maskingKeyProvider * @dataProvider maskingKeyProvider
* covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
* @todo I I wrote the dataProvider incorrectly, skipping for now * @todo I I wrote the dataProvider incorrectly, skipping for now
*/ */
public function testGetMaskingKey($mask) { public function testGetMaskingKey(string $mask): void {
$this->_frame->addBuffer(static::encode($this->_firstByteFinText)); $this->_frame->addBuffer(static::encode($this->_firstByteFinText));
$this->_frame->addBuffer(static::encode($this->_secondByteMaskedSPL)); $this->_frame->addBuffer(static::encode($this->_secondByteMaskedSPL));
$this->_frame->addBuffer($mask); $this->_frame->addBuffer($mask);
$this->assertEquals($mask, $this->_frame->getMaskingKey()); $this->assertEquals($mask, $this->_frame->getMaskingKey());
} }
/** public function testGetMaskingKeyOnUnmaskedPayload(): void {
* covers Ratchet\RFC6455\Messaging\Frame::getMaskingKey
*/
public function testGetMaskingKeyOnUnmaskedPayload() {
$frame = new Frame('Hello World!'); $frame = new Frame('Hello World!');
$this->assertEquals('', $frame->getMaskingKey()); $this->assertEquals('', $frame->getMaskingKey());
} }
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::getPayload
* @todo Move this test to bottom as it requires all methods of the class * @todo Move this test to bottom as it requires all methods of the class
*/ */
public function testUnframeFullMessage($unframed, $base_framed) { public function testUnframeFullMessage(string $unframed, string $base_framed): void {
$this->_frame->addBuffer(base64_decode($base_framed)); $this->_frame->addBuffer(base64_decode($base_framed));
$this->assertEquals($unframed, $this->_frame->getPayload()); $this->assertEquals($unframed, $this->_frame->getPayload());
} }
public static function messageFragmentProvider() { public static function messageFragmentProvider(): array {
return array( return array(
array(false, '', '', '', '', '') array(false, '', '', '', '', '')
); );
@ -313,9 +278,8 @@ class FrameTest extends TestCase {
/** /**
* @dataProvider UnframeMessageProvider * @dataProvider UnframeMessageProvider
* covers Ratchet\RFC6455\Messaging\Frame::getPayload
*/ */
public function testCheckPiecingTogetherMessage($msg, $encoded) { public function testCheckPiecingTogetherMessage(string $msg, string $encoded): void {
$framed = base64_decode($encoded); $framed = base64_decode($encoded);
for ($i = 0, $len = strlen($framed);$i < $len; $i++) { for ($i = 0, $len = strlen($framed);$i < $len; $i++) {
$this->_frame->addBuffer(substr($framed, $i, 1)); $this->_frame->addBuffer(substr($framed, $i, 1));
@ -323,12 +287,7 @@ class FrameTest extends TestCase {
$this->assertEquals($msg, $this->_frame->getPayload()); $this->assertEquals($msg, $this->_frame->getPayload());
} }
/** public function testLongCreate(): void {
* covers Ratchet\RFC6455\Messaging\Frame::__construct
* covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
* covers Ratchet\RFC6455\Messaging\Frame::getPayload
*/
public function testLongCreate() {
$len = 65525; $len = 65525;
$pl = $this->generateRandomString($len); $pl = $this->generateRandomString($len);
$frame = new Frame($pl, true, Frame::OP_PING); $frame = new Frame($pl, true, Frame::OP_PING);
@ -339,20 +298,13 @@ class FrameTest extends TestCase {
$this->assertEquals($pl, $frame->getPayload()); $this->assertEquals($pl, $frame->getPayload());
} }
/** public function testReallyLongCreate(): void {
* covers Ratchet\RFC6455\Messaging\Frame::__construct
* covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
*/
public function testReallyLongCreate() {
$len = 65575; $len = 65575;
$frame = new Frame($this->generateRandomString($len)); $frame = new Frame($this->generateRandomString($len));
$this->assertEquals($len, $frame->getPayloadLength()); $this->assertEquals($len, $frame->getPayloadLength());
} }
/**
* covers Ratchet\RFC6455\Messaging\Frame::__construct public function testExtractOverflow(): void {
* covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
*/
public function testExtractOverflow() {
$string1 = $this->generateRandomString(); $string1 = $this->generateRandomString();
$frame1 = new Frame($string1); $frame1 = new Frame($string1);
$string2 = $this->generateRandomString(); $string2 = $this->generateRandomString();
@ -367,10 +319,7 @@ class FrameTest extends TestCase {
$this->assertEquals($string2, $uncat->getPayload()); $this->assertEquals($string2, $uncat->getPayload());
} }
/** public function testEmptyExtractOverflow(): void {
* covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
*/
public function testEmptyExtractOverflow() {
$string = $this->generateRandomString(); $string = $this->generateRandomString();
$frame = new Frame($string); $frame = new Frame($string);
$this->assertEquals($string, $frame->getPayload()); $this->assertEquals($string, $frame->getPayload());
@ -378,10 +327,7 @@ class FrameTest extends TestCase {
$this->assertEquals($string, $frame->getPayload()); $this->assertEquals($string, $frame->getPayload());
} }
/** public function testGetContents(): void {
* covers Ratchet\RFC6455\Messaging\Frame::getContents
*/
public function testGetContents() {
$msg = 'The quick brown fox jumps over the lazy dog.'; $msg = 'The quick brown fox jumps over the lazy dog.';
$frame1 = new Frame($msg); $frame1 = new Frame($msg);
$frame2 = new Frame($msg); $frame2 = new Frame($msg);
@ -390,10 +336,7 @@ class FrameTest extends TestCase {
$this->assertEquals(strlen($frame1->getContents()) + 4, strlen($frame2->getContents())); $this->assertEquals(strlen($frame1->getContents()) + 4, strlen($frame2->getContents()));
} }
/** public function testMasking(): void {
* covers Ratchet\RFC6455\Messaging\Frame::maskPayload
*/
public function testMasking() {
$msg = 'The quick brown fox jumps over the lazy dog.'; $msg = 'The quick brown fox jumps over the lazy dog.';
$frame = new Frame($msg); $frame = new Frame($msg);
$frame->maskPayload(); $frame->maskPayload();
@ -401,10 +344,7 @@ class FrameTest extends TestCase {
$this->assertEquals($msg, $frame->getPayload()); $this->assertEquals($msg, $frame->getPayload());
} }
/** public function testUnMaskPayload(): void {
* covers Ratchet\RFC6455\Messaging\Frame::unMaskPayload
*/
public function testUnMaskPayload() {
$string = $this->generateRandomString(); $string = $this->generateRandomString();
$frame = new Frame($string); $frame = new Frame($string);
$frame->maskPayload()->unMaskPayload(); $frame->maskPayload()->unMaskPayload();
@ -412,10 +352,7 @@ class FrameTest extends TestCase {
$this->assertEquals($string, $frame->getPayload()); $this->assertEquals($string, $frame->getPayload());
} }
/** public function testGenerateMaskingKey(): void {
* covers Ratchet\RFC6455\Messaging\Frame::generateMaskingKey
*/
public function testGenerateMaskingKey() {
$dupe = false; $dupe = false;
$done = array(); $done = array();
for ($i = 0; $i < 10; $i++) { for ($i = 0; $i < 10; $i++) {
@ -429,27 +366,20 @@ class FrameTest extends TestCase {
$this->assertFalse($dupe); $this->assertFalse($dupe);
} }
/** public function testGivenMaskIsValid(): void {
* covers Ratchet\RFC6455\Messaging\Frame::maskPayload $this->expectException(\InvalidArgumentException::class);
*/
public function testGivenMaskIsValid() {
$this->setExpectedException('InvalidArgumentException');
$this->_frame->maskPayload('hello world'); $this->_frame->maskPayload('hello world');
} }
/** /**
* covers Ratchet\RFC6455\Messaging\Frame::maskPayload * @requires extension mbstring
*/ */
public function testGivenMaskIsValidAscii() { public function testGivenMaskIsValidAscii(): void {
if (!extension_loaded('mbstring')) { $this->expectException(\OutOfBoundsException::class);
$this->markTestSkipped("mbstring required for this test");
return;
}
$this->setExpectedException('OutOfBoundsException');
$this->_frame->maskPayload('x✖'); $this->_frame->maskPayload('x✖');
} }
protected function generateRandomString($length = 10, $addSpaces = true, $addNumbers = true) { protected function generateRandomString(int $length = 10, bool $addSpaces = true, bool $addNumbers = true): string {
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=[]{}'; // ยง $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"$%&/()=[]{}'; // ยง
$useChars = array(); $useChars = array();
for($i = 0; $i < $length; $i++) { for($i = 0; $i < $length; $i++) {
@ -473,11 +403,8 @@ class FrameTest extends TestCase {
* to set the payload length to 126 and then not recalculate it once the full length information was available. * to set the payload length to 126 and then not recalculate it once the full length information was available.
* *
* This is fixed by setting the defPayLen back to -1 before the underflow exception is thrown. * This is fixed by setting the defPayLen back to -1 before the underflow exception is thrown.
*
* covers Ratchet\RFC6455\Messaging\Frame::getPayloadLength
* covers Ratchet\RFC6455\Messaging\Frame::extractOverflow
*/ */
public function testFrameDeliveredOneByteAtATime() { public function testFrameDeliveredOneByteAtATime(): void {
$startHeader = "\x01\x7e\x01\x00"; // header for a text frame of 256 - non-final $startHeader = "\x01\x7e\x01\x00"; // header for a text frame of 256 - non-final
$framePayload = str_repeat("*", 256); $framePayload = str_repeat("*", 256);
$rawOverflow = "xyz"; $rawOverflow = "xyz";

View File

@ -9,13 +9,16 @@ use Ratchet\RFC6455\Messaging\MessageBuffer;
use React\EventLoop\Factory; use React\EventLoop\Factory;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
/**
* @covers Ratchet\RFC6455\Messaging\MessageBuffer
*/
class MessageBufferTest extends TestCase class MessageBufferTest extends TestCase
{ {
/** /**
* This is to test that MessageBuffer can handle a large receive * This is to test that MessageBuffer can handle a large receive
* buffer with many many frames without blowing the stack (pre-v0.4 issue) * buffer with many many frames without blowing the stack (pre-v0.4 issue)
*/ */
public function testProcessingLotsOfFramesInASingleChunk() { public function testProcessingLotsOfFramesInASingleChunk(): void {
$frame = new Frame('a', true, Frame::OP_TEXT); $frame = new Frame('a', true, Frame::OP_TEXT);
$frameRaw = $frame->getContents(); $frameRaw = $frame->getContents();
@ -26,7 +29,7 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount) { function (Message $message) use (&$messageCount): void {
$messageCount++; $messageCount++;
$this->assertEquals('a', $message->getPayload()); $this->assertEquals('a', $message->getPayload());
}, },
@ -39,7 +42,7 @@ class MessageBufferTest extends TestCase
$this->assertEquals(1000, $messageCount); $this->assertEquals(1000, $messageCount);
} }
public function testProcessingMessagesAsynchronouslyWhileBlockingInMessageHandler() { public function testProcessingMessagesAsynchronouslyWhileBlockingInMessageHandler(): void {
$loop = Factory::create(); $loop = Factory::create();
$frameA = new Frame('a', true, Frame::OP_TEXT); $frameA = new Frame('a', true, Frame::OP_TEXT);
@ -49,7 +52,7 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount, &$bReceived, $loop) { static function (Message $message) use (&$messageCount, &$bReceived, $loop): void {
$payload = $message->getPayload(); $payload = $message->getPayload();
$bReceived = $payload === 'b'; $bReceived = $payload === 'b';
@ -61,7 +64,7 @@ class MessageBufferTest extends TestCase
false false
); );
$loop->addPeriodicTimer(0.1, function () use ($messageBuffer, $frameB, $loop) { $loop->addPeriodicTimer(0.1, static function () use ($messageBuffer, $frameB, $loop): void {
$loop->stop(); $loop->stop();
$messageBuffer->onData($frameB->getContents()); $messageBuffer->onData($frameB->getContents());
}); });
@ -71,7 +74,7 @@ class MessageBufferTest extends TestCase
$this->assertTrue($bReceived); $this->assertTrue($bReceived);
} }
public function testInvalidFrameLength() { public function testInvalidFrameLength(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT); $frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents(); $frameRaw = $frame->getContents();
@ -93,7 +96,7 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount) { static function (Message $message) use (&$messageCount): void {
$messageCount++; $messageCount++;
}, },
function (Frame $frame) use (&$controlFrame) { function (Frame $frame) use (&$controlFrame) {
@ -109,13 +112,13 @@ class MessageBufferTest extends TestCase
$messageBuffer->onData($frameRaw); $messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount); $this->assertEquals(0, $messageCount);
$this->assertTrue($controlFrame instanceof Frame); $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode()); $this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_PROTOCOL], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2)))); $this->assertEquals([Frame::CLOSE_PROTOCOL], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
} }
public function testFrameLengthTooBig() { public function testFrameLengthTooBig(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT); $frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents(); $frameRaw = $frame->getContents();
@ -137,10 +140,10 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount) { static function (Message $message) use (&$messageCount): void {
$messageCount++; $messageCount++;
}, },
function (Frame $frame) use (&$controlFrame) { function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame); $this->assertNull($controlFrame);
$controlFrame = $frame; $controlFrame = $frame;
}, },
@ -153,12 +156,12 @@ class MessageBufferTest extends TestCase
$messageBuffer->onData($frameRaw); $messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount); $this->assertEquals(0, $messageCount);
$this->assertTrue($controlFrame instanceof Frame); $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode()); $this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2)))); $this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
} }
public function testFrameLengthBiggerThanMaxMessagePayload() { public function testFrameLengthBiggerThanMaxMessagePayload(): void {
$frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT); $frame = new Frame(str_repeat('a', 200), true, Frame::OP_TEXT);
$frameRaw = $frame->getContents(); $frameRaw = $frame->getContents();
@ -169,10 +172,10 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount) { static function (Message $message) use (&$messageCount): void {
$messageCount++; $messageCount++;
}, },
function (Frame $frame) use (&$controlFrame) { function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame); $this->assertNull($controlFrame);
$controlFrame = $frame; $controlFrame = $frame;
}, },
@ -185,12 +188,12 @@ class MessageBufferTest extends TestCase
$messageBuffer->onData($frameRaw); $messageBuffer->onData($frameRaw);
$this->assertEquals(0, $messageCount); $this->assertEquals(0, $messageCount);
$this->assertTrue($controlFrame instanceof Frame); $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode()); $this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2)))); $this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
} }
public function testSecondFrameLengthPushesPastMaxMessagePayload() { public function testSecondFrameLengthPushesPastMaxMessagePayload(): void {
$frame = new Frame(str_repeat('a', 200), false, Frame::OP_TEXT); $frame = new Frame(str_repeat('a', 200), false, Frame::OP_TEXT);
$firstFrameRaw = $frame->getContents(); $firstFrameRaw = $frame->getContents();
$frame = new Frame(str_repeat('b', 200), true, Frame::OP_TEXT); $frame = new Frame(str_repeat('b', 200), true, Frame::OP_TEXT);
@ -202,10 +205,10 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) use (&$messageCount) { static function (Message $message) use (&$messageCount): void {
$messageCount++; $messageCount++;
}, },
function (Frame $frame) use (&$controlFrame) { function (Frame $frame) use (&$controlFrame): void {
$this->assertNull($controlFrame); $this->assertNull($controlFrame);
$controlFrame = $frame; $controlFrame = $frame;
}, },
@ -220,7 +223,7 @@ class MessageBufferTest extends TestCase
$messageBuffer->onData(substr($secondFrameRaw, 0, 150)); $messageBuffer->onData(substr($secondFrameRaw, 0, 150));
$this->assertEquals(0, $messageCount); $this->assertEquals(0, $messageCount);
$this->assertTrue($controlFrame instanceof Frame); $this->assertInstanceOf(Frame::class, $controlFrame);
$this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode()); $this->assertEquals(Frame::OP_CLOSE, $controlFrame->getOpcode());
$this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2)))); $this->assertEquals([Frame::CLOSE_TOO_BIG], array_merge(unpack('n*', substr($controlFrame->getPayload(), 0, 2))));
} }
@ -258,15 +261,15 @@ class MessageBufferTest extends TestCase
* @param string $phpConfigurationValue * @param string $phpConfigurationValue
* @param int $expectedLimit * @param int $expectedLimit
*/ */
public function testMemoryLimits($phpConfigurationValue, $expectedLimit) { public function testMemoryLimits(string $phpConfigurationValue, int $expectedLimit): void {
$method = new \ReflectionMethod('Ratchet\RFC6455\Messaging\MessageBuffer', 'getMemoryLimit'); $method = new \ReflectionMethod(MessageBuffer::class, 'getMemoryLimit');
$method->setAccessible(true); $method->setAccessible(true);
$actualLimit = $method->invoke(null, $phpConfigurationValue); $actualLimit = $method->invoke(null, $phpConfigurationValue);
$this->assertSame($expectedLimit, $actualLimit); $this->assertSame($expectedLimit, $actualLimit);
} }
public function phpConfigurationProvider() { public function phpConfigurationProvider(): array {
return [ return [
'without unit type, just bytes' => ['500', 500], 'without unit type, just bytes' => ['500', 500],
'1 GB with big "G"' => ['1G', 1 * 1024 * 1024 * 1024], '1 GB with big "G"' => ['1G', 1 * 1024 * 1024 * 1024],
@ -281,14 +284,13 @@ class MessageBufferTest extends TestCase
]; ];
} }
/** public function testInvalidMaxFramePayloadSizes(): void {
* @expectedException \InvalidArgumentException $this->expectException(\InvalidArgumentException::class);
*/
public function testInvalidMaxFramePayloadSizes() { new MessageBuffer(
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) {}, static function (Message $message): void {},
function (Frame $frame) {}, static function (Frame $frame): void {},
false, false,
null, null,
0, 0,
@ -296,14 +298,13 @@ class MessageBufferTest extends TestCase
); );
} }
/** public function testInvalidMaxMessagePayloadSizes(): void {
* @expectedException \InvalidArgumentException $this->expectException(\InvalidArgumentException::class);
*/
public function testInvalidMaxMessagePayloadSizes() { new MessageBuffer(
$messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) {}, static function (Message $message): void {},
function (Frame $frame) {}, static function (Frame $frame): void {},
false, false,
null, null,
0x8000000000000000, 0x8000000000000000,
@ -318,9 +319,8 @@ class MessageBufferTest extends TestCase
* @param int $expectedLimit * @param int $expectedLimit
* *
* @runInSeparateProcess * @runInSeparateProcess
* @requires PHP 7.0
*/ */
public function testIniSizes($phpConfigurationValue, $expectedLimit) { public function testIniSizes(string $phpConfigurationValue, int $expectedLimit): void {
$value = @ini_set('memory_limit', $phpConfigurationValue); $value = @ini_set('memory_limit', $phpConfigurationValue);
if ($value === false) { if ($value === false) {
$this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage"); $this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage");
@ -328,8 +328,8 @@ class MessageBufferTest extends TestCase
$messageBuffer = new MessageBuffer( $messageBuffer = new MessageBuffer(
new CloseFrameChecker(), new CloseFrameChecker(),
function (Message $message) {}, static function (Message $message): void {},
function (Frame $frame) {}, static function (Frame $frame): void {},
false, false,
null null
); );
@ -349,9 +349,8 @@ class MessageBufferTest extends TestCase
/** /**
* @runInSeparateProcess * @runInSeparateProcess
* @requires PHP 7.0
*/ */
public function testInvalidIniSize() { public function testInvalidIniSize(): void {
$value = @ini_set('memory_limit', 'lots of memory'); $value = @ini_set('memory_limit', 'lots of memory');
if ($value === false) { if ($value === false) {
$this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage"); $this->markTestSkipped("Does not support setting the memory_limit lower than current memory_usage");

View File

@ -13,20 +13,20 @@ class MessageTest extends TestCase {
/** @var Message */ /** @var Message */
protected $message; protected $message;
public function setUp() { protected function setUp(): void {
$this->message = new Message; $this->message = new Message;
} }
public function testNoFrames() { public function testNoFrames(): void {
$this->assertFalse($this->message->isCoalesced()); $this->assertFalse($this->message->isCoalesced());
} }
public function testNoFramesOpCode() { public function testNoFramesOpCode(): void {
$this->setExpectedException('UnderflowException'); $this->expectException(\UnderflowException::class);
$this->message->getOpCode(); $this->message->getOpCode();
} }
public function testFragmentationPayload() { public function testFragmentationPayload(): void {
$a = 'Hello '; $a = 'Hello ';
$b = 'World!'; $b = 'World!';
$f1 = new Frame($a, false); $f1 = new Frame($a, false);
@ -36,13 +36,13 @@ class MessageTest extends TestCase {
$this->assertEquals($a . $b, $this->message->getPayload()); $this->assertEquals($a . $b, $this->message->getPayload());
} }
public function testUnbufferedFragment() { public function testUnbufferedFragment(): void {
$this->message->addFrame(new Frame('The quick brow', false)); $this->message->addFrame(new Frame('The quick brow', false));
$this->setExpectedException('UnderflowException'); $this->expectException(\UnderflowException::class);
$this->message->getPayload(); $this->message->getPayload();
} }
public function testGetOpCode() { public function testGetOpCode(): void {
$this->message $this->message
->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT)) ->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT))
->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE)) ->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE))
@ -51,7 +51,7 @@ class MessageTest extends TestCase {
$this->assertEquals(Frame::OP_TEXT, $this->message->getOpCode()); $this->assertEquals(Frame::OP_TEXT, $this->message->getOpCode());
} }
public function testGetUnBufferedPayloadLength() { public function testGetUnBufferedPayloadLength(): void {
$this->message $this->message
->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT)) ->addFrame(new Frame('The quick brow', false, Frame::OP_TEXT))
->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE)) ->addFrame(new Frame('n fox jumps ov', false, Frame::OP_CONTINUE))