Core\Test::answerSocket
Core\Test::answerSocket() gives a test a fake WebSocket service. You give it a URL and a list of messages. A socket your program opens to that URL with Core\Http\Client::openSocket receives the messages in order. After the last message, receive returns null, because the service has closed the connection.
A string is sent as a text message, and bytes as a binary message. The option protocol sets the subprotocol the service chooses, from the ones the program offers. Core\Test::sentSocket returns the messages your program sent.
After the first call, the program makes no network connections. A URL that ends in * matches every URL that starts with the text before it. An exact URL wins, and then the longest prefix wins.
A test and a command-line program can call answerSocket. In server code, it throws a LogicError. Server code is a request, a connection, a scheduled task or a queued job. There is one exception: a request that a test sends with Core\Test::request may call it.
The examples below show a service that sends messages, which service a URL gets, and a price feed client.
Parameters
$urlstringThe URL this peer is for. Give the whole URL, or a prefix that ends in*. A prefix matches every URL that starts with the text before the*. The URL given toCore\Http\Client::openSocketis compared with this text, and no host is looked up.openSocketstill throws an error for a URL whose scheme is notwsorwss.$framesarray<string|bytes>The messages the peer sends, in order. Each message is one frame. Astringis a text message, andbytesis a binary message. The socket'ssendandsendBytesmethods write the same two kinds. After the last frame,receivereturnsnull, which means the peer closed the socket.
Options
protocolstringoptionalThe subprotocol the peer chooses. A subprotocol is a name that both sides agree on when the socket opens. It must be one of the names your call offered inprotocols. If the peer chooses a name that was never offered,openSocketthrows an error, as it does with a real server. If you leave it out, the peer chooses no subprotocol.
Return value
Returns void. Nothing. Each call adds one more peer, so a test can give a peer for each socket it opens. An exact URL wins over a prefix, and the longest prefix wins among prefixes. Two sockets opened to one URL each receive all of that peer's frames, from the first one.
Errors
LogicErrorThe call runs in a server, such as in a request, a connection, a scheduled task or a queued job. There is one exception: a request that a test sends withCore\Test::requestmay call it. Tests and command-line programs may always call it.
Changelog
| Version | Change |
|---|---|
0.0.6 | Core\Test::answerHttp, Core\Test::answerSocket, Core\Test::tlsSession and Core\Test::scriptAnswers throw a LogicError in a request, a connection, a scheduled task and a queued job. They work in a test, and in a request or a program that a test starts. They also work in a command-line program. |
Examples
A peer that sends messages
<?nvs// Shows how to give a WebSocket a fixed list of messages to receive in a test.
use Core\Http\Client;use Core\Test;
// The peer sends two text messages and one binary message. Then it closes.Test::answerSocket('wss://chat.example.com/room', ['hello', 'welcome', 'OK' as bytes]);
var $socket = Client::openSocket('wss://chat.example.com/room');
// `receive` returns the messages in order. After the last one, it returns `null`.// This prints `text hello`, `text welcome` and `bytes 2`.var $message = $socket->receive();while ($message != null) { if ($message->text() != null) { echo 'text ', $message->text() ?? '', "\n"; } else { echo 'bytes ', Core\Bytes::length($message->bytes() ?? ('' as tainted bytes)), "\n"; } $message = $socket->receive();}echo "closed\n";text hellotext welcomebytes 2closedWhich peer a url gets
<?nvs// Shows which scripted peer a socket gets, and how a peer chooses a subprotocol.
use Core\Http\Client;use Core\Test;
// A URL that ends in `*` matches every URL that starts with the text before it.Test::answerSocket('wss://feed.example.com/*', ['any feed']);Test::answerSocket('wss://feed.example.com/prices', ['prices feed'], { protocol: 'prices.v2' });
// The whole URL matches the second peer. An exact match always wins.// The call offers two subprotocols, and the peer chooses `prices.v2`.var $prices = Client::openSocket('wss://feed.example.com/prices', { protocols: ['prices.v1', 'prices.v2'],});// This prints `prices feed` and `prices.v2`.echo $prices->receive()?->text() ?? '-', "\n";echo $prices->protocol() ?? 'none', "\n";
// Only the prefix matches. That peer chooses no subprotocol.// This prints `any feed` and `none`.var $news = Client::openSocket('wss://feed.example.com/news');echo $news->receive()?->text() ?? '-', "\n";echo $news->protocol() ?? 'none', "\n";
// No peer matches this URL, so `openSocket` throws a `LogicError`.// The program does not use the network for it.try { var $other = Client::openSocket('wss://other.example.com/');} catch (LogicError $error) { echo "LogicError\n";}prices feedprices.v2any feednoneLogicErrorA price feed client
<?nvs// Shows how to test code that uses a WebSocket service, with no real server.
use Core\Http\Client;use Core\Socket\Message;use Core\Test;
class PriceFeed{ // Subscribes to one product and returns the last price the service sends. // The price comes from outside the program, so its type is `tainted string`. public static function lastPrice(string $sku): tainted string { var $socket = Client::openSocket('wss://prices.example.com/live'); $socket->send('subscribe ' . $sku); tainted string $last = 'none'; var $message = $socket->receive(); while ($message != null) { $last = $message->text() ?? $last; $message = $socket->receive(); } $socket->close(); return $last; }}
// The test service sends three prices. Then it closes the connection.Test::answerSocket('wss://prices.example.com/live', ['12.00', '12.50', '11.75']);
// This prints `11.75`.echo PriceFeed::lastPrice('mug'), "\n";
// `Test::sentSocket` returns the messages the code sent.// This prints `subscribe mug`.foreach (Test::sentSocket() as Message $frame) { echo $frame->text() ?? '-', "\n";}11.75subscribe mug