react-websocket/tests/WebSocketProtocolTest.php

100 lines
2.8 KiB
PHP
Raw Permalink Normal View History

2024-02-21 20:23:24 +00:00
<?php
namespace NoccyLabs\React\WebSocket;
use PHPUnit\Framework\Attributes\CoversClass;
2024-02-22 00:22:52 +00:00
#[CoversClass(WebSocketProtocol::class)]
class WebSocketProtocolTest extends \PHPUnit\Framework\TestCase
2024-02-21 20:23:24 +00:00
{
public function testEncodingFrames()
{
2024-02-22 00:22:52 +00:00
$codec = new WebSocketProtocol();
2024-02-21 20:23:24 +00:00
$msg = $codec->encode([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_PING,
2024-02-21 20:23:24 +00:00
'payload'=>"ping"
]);
$this->assertEquals("\x89\x04ping", $msg);
$msg = $codec->encode([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh"]);
$this->assertEquals("\x81\x08abcdefgh", $msg);
$msg = $codec->encode([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh",
'masked'=>true,
'mask'=>"\x00\x00\x00\x00"
]);
$this->assertEquals("\x81\x88\x00\x00\x00\x00abcdefgh", $msg);
$msg = $codec->encode([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh",
'masked'=>true,
'mask'=>"\x00\xFF\x00\xFF"
]);
$this->assertEquals("\x81\x88\x00\xFF\x00\xFFa\x9dc\x9be\x99g\x97", $msg);
}
public function testDecodingFrames()
{
2024-02-22 00:22:52 +00:00
$codec = new WebSocketProtocol();
2024-02-21 20:23:24 +00:00
$msg = $codec->decode("\x89\x04ping");
$this->assertEquals([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_PING,
2024-02-21 20:23:24 +00:00
'payload'=>"ping",
'final'=>true,
'rsv1'=>false,
'rsv2'=>false,
'rsv3'=>false,
'length'=>4,
'masked'=>false
], $msg);
$msg = $codec->decode("\x81\x08abcdefgh");
$this->assertEquals([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh",
'final'=>true,
'rsv1'=>false,
'rsv2'=>false,
'rsv3'=>false,
'length'=>8,
'masked'=>false
], $msg);
$msg = $codec->decode("\x81\x88\x00\x00\x00\x00abcdefgh");
$this->assertEquals([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh",
'final'=>true,
'rsv1'=>false,
'rsv2'=>false,
'rsv3'=>false,
'length'=>8,
'masked'=>true,
'mask'=>"\x00\x00\x00\x00"
], $msg);
$msg = $codec->decode("\x81\x88\x00\xFF\x00\xFFa\x9dc\x9be\x99g\x97");
$this->assertEquals([
2024-02-21 23:15:22 +00:00
'opcode'=>WebSocketConnection::OP_FRAME_TEXT,
2024-02-21 20:23:24 +00:00
'payload'=>"abcdefgh",
'final'=>true,
'rsv1'=>false,
'rsv2'=>false,
'rsv3'=>false,
'length'=>8,
'masked'=>true,
'mask'=>"\x00\xFF\x00\xFF"
], $msg);
}
}