laravel-websockets/tests/TestCase.php

441 lines
12 KiB
PHP
Raw Normal View History

2018-11-25 22:43:43 +00:00
<?php
2020-09-10 19:59:26 +00:00
namespace BeyondCode\LaravelWebSockets\Test;
use BeyondCode\LaravelWebSockets\Contracts\ChannelManager;
use BeyondCode\LaravelWebSockets\Contracts\StatisticsCollector;
use BeyondCode\LaravelWebSockets\Contracts\StatisticsStore;
2020-09-10 19:59:49 +00:00
use GuzzleHttp\Psr7\Request;
2020-09-04 18:50:38 +00:00
use Illuminate\Support\Facades\Redis;
2020-09-10 19:59:49 +00:00
use Orchestra\Testbench\BrowserKit\TestCase as Orchestra;
use React\EventLoop\Factory as LoopFactory;
2020-09-10 19:59:26 +00:00
abstract class TestCase extends Orchestra
2018-11-25 22:43:43 +00:00
{
/**
* A test Pusher server.
*
2020-09-10 19:59:26 +00:00
* @var \BeyondCode\LaravelWebSockets\Server\WebSocketHandler
*/
protected $pusherServer;
/**
* The test Channel manager.
*
2020-09-10 19:59:26 +00:00
* @var \BeyondCode\LaravelWebSockets\Contracts\ChannelManager
*/
protected $channelManager;
/**
2020-09-10 19:59:26 +00:00
* The test Channel manager.
*
2020-09-10 19:59:26 +00:00
* @var \BeyondCode\LaravelWebSockets\Contracts\StatisticsCollector
*/
2020-09-10 19:59:26 +00:00
protected $statisticsCollector;
2020-09-04 18:50:38 +00:00
/**
2020-09-10 19:59:26 +00:00
* The test Channel manager.
2020-09-04 18:50:38 +00:00
*
2020-09-10 19:59:26 +00:00
* @var \BeyondCode\LaravelWebSockets\Contracts\StatisticsStore
2020-09-04 18:50:38 +00:00
*/
2020-09-10 19:59:26 +00:00
protected $statisticsStore;
2020-09-04 18:50:38 +00:00
/**
* Get the loop instance.
*
* @var \React\EventLoop\LoopInterface
*/
protected $loop;
2020-09-10 19:59:26 +00:00
/**
* The Redis manager instance.
*
* @var \Illuminate\Redis\RedisManager
*/
protected $redis;
/**
* Get the replication mode it is used for testing.
*
* @var string
*/
protected $replicationMode = 'local';
2020-08-14 10:53:14 +00:00
/**
* {@inheritdoc}
*/
public function setUp(): void
2018-11-27 20:56:25 +00:00
{
parent::setUp();
2020-09-04 18:50:38 +00:00
$this->loop = LoopFactory::create();
2020-09-10 19:59:26 +00:00
$this->replicationMode = getenv('REPLICATION_MODE') ?: 'local';
2020-08-23 16:12:22 +00:00
2020-09-10 19:59:26 +00:00
$this->resetDatabase();
2020-08-23 16:12:22 +00:00
$this->loadLaravelMigrations(['--database' => 'sqlite']);
2020-09-11 05:47:28 +00:00
$this->loadMigrationsFrom(__DIR__.'/database/migrations');
2020-08-23 16:12:22 +00:00
$this->withFactories(__DIR__.'/database/factories');
2020-09-10 19:59:26 +00:00
$this->registerManagers();
2020-09-10 19:59:26 +00:00
$this->registerStatisticsCollectors();
2020-09-10 19:59:26 +00:00
$this->registerStatisticsStores();
2020-09-03 13:31:19 +00:00
$this->pusherServer = $this->app->make(config('websockets.handlers.websocket'));
2020-09-10 19:59:26 +00:00
if ($this->replicationMode === 'redis') {
$this->registerRedis();
}
2020-09-15 14:03:28 +00:00
if (method_exists($this->channelManager, 'getPublishClient')) {
$this->getPublishClient()->resetAssertions();
$this->getSubscribeClient()->resetAssertions();
}
2018-11-27 20:56:25 +00:00
}
2020-08-14 10:53:14 +00:00
/**
* {@inheritdoc}
*/
2018-11-25 22:43:43 +00:00
protected function getPackageProviders($app)
{
return [
\BeyondCode\LaravelWebSockets\WebSocketsServiceProvider::class,
2020-08-23 16:12:22 +00:00
TestServiceProvider::class,
];
2018-11-25 22:43:43 +00:00
}
2020-08-14 10:53:14 +00:00
/**
* {@inheritdoc}
*/
2020-09-10 19:59:26 +00:00
public function getEnvironmentSetUp($app)
2018-11-25 22:43:43 +00:00
{
2020-09-10 19:59:26 +00:00
$this->replicationMode = getenv('REPLICATION_MODE') ?: 'local';
2020-08-23 16:12:22 +00:00
$app['config']->set('database.default', 'sqlite');
$app['config']->set('database.connections.sqlite', [
2020-09-10 19:59:26 +00:00
'driver' => 'sqlite',
2020-08-23 16:12:22 +00:00
'database' => __DIR__.'/database.sqlite',
2020-09-10 19:59:26 +00:00
'prefix' => '',
2020-08-23 16:12:22 +00:00
]);
2020-09-10 19:59:26 +00:00
$app['config']->set(
'broadcasting.connections.websockets', [
'driver' => 'pusher',
'key' => 'TestKey',
'secret' => 'TestSecret',
'app_id' => '1234',
'options' => [
'cluster' => 'mt1',
'encrypted' => true,
'host' => '127.0.0.1',
'port' => 6001,
'scheme' => 'http',
],
]
);
$app['config']->set('auth.providers.users.model', Models\User::class);
$app['config']->set('app.key', 'wslxrEFGWY6GfGhvN9L3wH3KSRJQQpBD');
$app['config']->set('database.redis.default', [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD', null),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
]);
$app['config']->set(
'websockets.replication.mode', $this->replicationMode
);
if ($this->replicationMode === 'redis') {
$app['config']->set('broadcasting.default', 'pusher');
$app['config']->set('cache.default', 'redis');
}
2018-12-01 13:17:32 +00:00
$app['config']->set('websockets.apps', [
2018-11-25 22:43:43 +00:00
[
2018-12-01 13:12:15 +00:00
'name' => 'Test App',
'id' => '1234',
2018-12-01 12:57:02 +00:00
'key' => 'TestKey',
2018-12-01 14:59:46 +00:00
'secret' => 'TestSecret',
'host' => 'localhost',
'capacity' => null,
2018-12-01 15:24:36 +00:00
'enable_client_messages' => false,
2018-12-03 10:58:42 +00:00
'enable_statistics' => true,
2020-08-18 13:04:52 +00:00
'allowed_origins' => [],
],
[
'name' => 'Origin Test App',
'id' => '1234',
'key' => 'TestOrigin',
'secret' => 'TestSecret',
'capacity' => null,
'enable_client_messages' => false,
'enable_statistics' => true,
'allowed_origins' => [
'test.origin.com',
],
2018-12-01 14:59:46 +00:00
],
2020-09-10 19:59:26 +00:00
[
'name' => 'Test App 2',
'id' => '12345',
'key' => 'TestKey2',
'secret' => 'TestSecret2',
'host' => 'localhost',
'capacity' => null,
'enable_client_messages' => false,
'enable_statistics' => true,
'allowed_origins' => [],
],
2018-11-25 22:43:43 +00:00
]);
2018-12-03 12:33:00 +00:00
2020-09-10 19:59:26 +00:00
$app['config']->set('websockets.replication.modes', [
'local' => [
'channel_manager' => \BeyondCode\LaravelWebSockets\ChannelManagers\LocalChannelManager::class,
'collector' => \BeyondCode\LaravelWebSockets\Statistics\Collectors\MemoryCollector::class,
],
'redis' => [
'channel_manager' => \BeyondCode\LaravelWebSockets\ChannelManagers\RedisChannelManager::class,
'connection' => 'default',
'collector' => \BeyondCode\LaravelWebSockets\Statistics\Collectors\RedisCollector::class,
],
2020-08-13 13:18:14 +00:00
]);
2020-09-10 19:59:26 +00:00
}
2020-08-13 13:18:14 +00:00
2020-09-10 19:59:26 +00:00
/**
* Register the managers that are not resolved
* by the package service provider.
*
* @return void
*/
protected function registerManagers()
{
$this->app->singleton(ChannelManager::class, function () {
$mode = config('websockets.replication.mode', $this->replicationMode);
2020-08-13 19:52:12 +00:00
2020-09-10 19:59:26 +00:00
$class = config("websockets.replication.modes.{$mode}.channel_manager");
2020-08-13 19:52:12 +00:00
2020-09-10 19:59:26 +00:00
return new $class($this->loop, Mocks\RedisFactory::class);
});
2020-08-13 19:52:12 +00:00
2020-09-10 19:59:26 +00:00
$this->channelManager = $this->app->make(ChannelManager::class);
}
/**
2020-09-11 13:39:56 +00:00
* Register the statistics collectors.
2020-09-10 19:59:26 +00:00
*
* @return void
*/
protected function registerStatisticsCollectors()
{
$this->statisticsCollector = $this->app->make(StatisticsCollector::class);
2020-09-11 13:39:56 +00:00
$this->artisan('websockets:flush');
2018-11-25 22:43:43 +00:00
}
/**
2020-09-10 19:59:26 +00:00
* Register the statistics stores that are
* not resolved by the package service provider.
*
2020-09-10 19:59:26 +00:00
* @return void
*/
protected function registerStatisticsStores()
{
$this->app->singleton(StatisticsStore::class, function () {
$class = config('websockets.statistics.store');
return new $class;
});
$this->statisticsStore = $this->app->make(StatisticsStore::class);
}
/**
* Register the Redis components for testing.
*
* @return void
*/
protected function registerRedis()
{
$this->redis = Redis::connection();
$this->redis->flushdb();
}
/**
* Get the websocket connection for a specific key.
*
* @param string $appKey
* @param array $headers
2020-09-10 19:59:26 +00:00
* @return Mocks\Connection
*/
2020-09-10 19:59:26 +00:00
protected function newConnection(string $appKey = 'TestKey', array $headers = [])
{
2020-09-10 19:59:26 +00:00
$connection = new Mocks\Connection;
$connection->httpRequest = new Request('GET', "/?appKey={$appKey}", $headers);
return $connection;
}
/**
* Get a connected websocket connection.
*
* @param array $channelsToJoin
* @param string $appKey
* @param array $headers
2020-09-10 19:59:26 +00:00
* @return Mocks\Connection
*/
2020-09-10 19:59:26 +00:00
protected function newActiveConnection(array $channelsToJoin = [], string $appKey = 'TestKey', array $headers = [])
{
2020-09-10 19:59:26 +00:00
$connection = $this->newConnection($appKey, $headers);
$this->pusherServer->onOpen($connection);
foreach ($channelsToJoin as $channel) {
2020-09-10 19:59:26 +00:00
$message = new Mocks\Message([
'event' => 'pusher:subscribe',
'data' => [
'channel' => $channel,
],
]);
$this->pusherServer->onMessage($connection, $message);
}
return $connection;
}
/**
* Join a presence channel.
*
* @param string $channel
2020-09-10 19:59:26 +00:00
* @param array $user
2020-09-11 12:57:51 +00:00
* @param string $appKey
* @param array $headers
2020-09-10 19:59:26 +00:00
* @return Mocks\Connection
*/
2020-09-11 12:57:51 +00:00
protected function newPresenceConnection($channel, array $user = [], string $appKey = 'TestKey', array $headers = [])
{
2020-09-11 12:57:51 +00:00
$connection = $this->newConnection($appKey, $headers);
$this->pusherServer->onOpen($connection);
2020-09-10 19:59:26 +00:00
$user = $user ?: [
'user_id' => 1,
2020-09-10 19:59:26 +00:00
'user_info' => ['name' => 'Rick'],
];
2020-09-10 19:59:26 +00:00
$signature = "{$connection->socketId}:{$channel}:".json_encode($user);
$hash = hash_hmac('sha256', $signature, $connection->app->secret);
2020-09-10 19:59:26 +00:00
$message = new Mocks\Message([
'event' => 'pusher:subscribe',
'data' => [
2020-09-10 19:59:26 +00:00
'auth' => "{$connection->app->key}:{$hash}",
'channel' => $channel,
2020-09-10 19:59:26 +00:00
'channel_data' => json_encode($user),
],
]);
$this->pusherServer->onMessage($connection, $message);
return $connection;
}
/**
2020-09-10 19:59:26 +00:00
* Join a private channel.
*
2020-09-10 19:59:26 +00:00
* @param string $channel
2020-09-11 12:57:51 +00:00
* @param string $appKey
* @param array $headers
2020-09-10 19:59:26 +00:00
* @return Mocks\Connection
*/
2020-09-11 12:57:51 +00:00
protected function newPrivateConnection($channel, string $appKey = 'TestKey', array $headers = [])
{
2020-09-11 12:57:51 +00:00
$connection = $this->newConnection($appKey, $headers);
2020-09-10 19:59:26 +00:00
$this->pusherServer->onOpen($connection);
$signature = "{$connection->socketId}:{$channel}";
$hash = hash_hmac('sha256', $signature, $connection->app->secret);
$message = new Mocks\Message([
'event' => 'pusher:subscribe',
'data' => [
'auth' => "{$connection->app->key}:{$hash}",
'channel' => $channel,
],
]);
$this->pusherServer->onMessage($connection, $message);
return $connection;
}
/**
2020-09-10 19:59:26 +00:00
* Get the subscribed client for the replication.
*
2020-09-10 19:59:26 +00:00
* @return Mocks\LazyClient
*/
2020-09-10 19:59:26 +00:00
protected function getSubscribeClient()
{
2020-09-10 19:59:26 +00:00
return $this->channelManager->getSubscribeClient();
}
2020-09-04 19:26:46 +00:00
2020-09-10 19:59:26 +00:00
/**
* Get the publish client for the replication.
*
* @return Mocks\LazyClient
*/
protected function getPublishClient()
{
return $this->channelManager->getPublishClient();
}
/**
2020-09-10 19:59:26 +00:00
* Reset the database.
*
* @return void
*/
2020-09-10 19:59:26 +00:00
protected function resetDatabase()
{
2020-09-10 19:59:26 +00:00
file_put_contents(__DIR__.'/database.sqlite', null);
}
2020-08-14 12:35:36 +00:00
protected function runOnlyOnRedisReplication()
{
2020-09-10 19:59:26 +00:00
if ($this->replicationMode !== 'redis') {
$this->markTestSkipped('Skipped test because the replication mode is not set to Redis.');
2020-08-14 12:35:36 +00:00
}
}
protected function runOnlyOnLocalReplication()
{
2020-09-10 19:59:26 +00:00
if ($this->replicationMode !== 'local') {
$this->markTestSkipped('Skipped test because the replication mode is not set to Local.');
2020-08-14 16:53:30 +00:00
}
}
protected function skipOnRedisReplication()
{
2020-09-10 19:59:26 +00:00
if ($this->replicationMode === 'redis') {
$this->markTestSkipped('Skipped test because the replication mode is Redis.');
2020-08-14 16:53:30 +00:00
}
}
protected function skipOnLocalReplication()
{
2020-09-10 19:59:26 +00:00
if ($this->replicationMode === 'local') {
$this->markTestSkipped('Skipped test because the replication mode is Local.');
2020-08-14 12:35:36 +00:00
}
}
2018-12-04 21:22:33 +00:00
}