phptestingwebsocketphpunitratchet

Websocket Testing [Functional]


I am using Ratchet for websockets in PHP. I was able to write unit (phpspec) and acceptance tests (behat) for websockets but I cannot find a way on how to test the connection to the websocket server by using a functional phpunit test.. I think a test, which checks if the connection is up and running, would be very important. I thought of something like the following:

  1. Create a (ratchet) client in phpunit
  2. Connect to ws url (e.g. client->connect(host, port, ...)
  3. ping websocket / send / receive some messages (call methods of client, e.g. client->push(..)..)

The problem is, that I don't know which class is responsible for establishing the connection (creating a client which can request the websocket) in Ratchet and how a test would then look like. How can I create a Ratchet Client in order to be able to connect and request a websocket in phpunit functional test? (similar to e.g. a webclient within a standard phpunit functional test)

As an example, within a functional test for a feature, I could do the following:

$client = static::createClient();
$client->request('GET', '/book/3', array(), array(), array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
$response = $client->getResponse();
$this->assertEquals(
    440,
    $response->getStatusCode()
);

Or e.g. create an authenticated client instead of an anonymous. How would it be possible, to "translate" this functional test into a ratchet websocket one?


Solution

  • I hope this partially solves your question of what part of the Ratchet Websocket is responsible of making a connection.

    The test itself will probably not work, I am not that experienced with testing in PHP although it should put you on the right path.

    public function testCanConnect()
        {
            \Ratchet\Client\connect('ws://127.0.0.1:8080')->then(function($conn) {
                $conn->on('message', function($msg) use ($conn) {
                    print $msg."\n";
                    $this->assertEquals('true',true);
                    $this->assertEquals("Hello World",$msg);
                    $conn->close();
                });
                $conn->send('Hello World!');
            }, function ($e) {
                echo "Could not connect: {$e->getMessage()}\n";
            });
        }
    

    If you have any further questions please let me know.