mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 14:34:04 +00:00
Cache prefixing logic rewrite, session scoping improvements, tests refactor (#43)
* Run cache tests on all supported drivers * update ci healthcheck for memcached * remove memcached healthcheck * fix typos in test comments, expand internal.md [ci skip] * add empty line [ci skip] * switch to using $store->setPrefix() * add dynamodb * refactor try-finally to try-catch * remove unnecessary clearResolvedInstances() call * add dual Cache:: and cache() assertions * add apc * Flush APCu cache in test setup * Revert "add dual Cache:: and cache() assertions" This reverts commit a0bab162fbe2dd0d25e7056ceca4fb7ce54efc77. * phpstan fix * Add logic for scoping 'file' disks to FilesystemTenancyBootstrapper * minor changes, add todos * refactor how the session.connection is used in the DB session bootstrapper * add session forgery prevention logic to the db session bootstrapper * only use the fs bootstrapper for file disk in 'cache data is separated' dataset * minor session scoping test changes * Add session scoping logic to FilesystemTenancyBootstrapper, correctly update disk roots even with storage_path_tenancy disabled * Fix code style (php-cs-fixer) * update docblock * make not-null check more explicit * separate bootstrapper tests, fix swapped test names for two tests * refactor cache bootstrapper tests * resolve global cache todo * expand tests: session separation tests, more filesystem separation assertions; change prefix_base-type config keys to templates/formats * add apc session scoping test, various session separation bugfixes * phpstan + minor logic fixes * prefix_format -> prefix * fix database session separation test * revert composer.json changes, update laravel dependencies to expected next release * only run session scoping logic in cache bootstrapper for redis, memcached, dynamodb, apc; update gitattributes * tenancy.central_domains -> tenancy.identification.central_domains * db session separation test: add datasets --------- Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
This commit is contained in:
parent
943b960718
commit
eecf6f21c8
40 changed files with 1856 additions and 1177 deletions
248
tests/Bootstrappers/BootstrapperTest.php
Normal file
248
tests/Bootstrappers/BootstrapperTest.php
Normal file
|
|
@ -0,0 +1,248 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Redis;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Filesystem\FilesystemAdapter;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTagsBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->mockConsoleOutput = false;
|
||||
|
||||
config([
|
||||
'cache.default' => 'redis',
|
||||
'tenancy.cache.stores' => ['redis'],
|
||||
]);
|
||||
|
||||
Event::listen(
|
||||
TenantCreated::class,
|
||||
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener()
|
||||
);
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('database data is separated', function () {
|
||||
config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
pest()->artisan('tenants:migrate');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
// Create Foo user
|
||||
DB::table('users')->insert(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||
expect(DB::table('users')->get())->toHaveCount(1);
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
// Assert Foo user is not in this DB
|
||||
expect(DB::table('users')->get())->toHaveCount(0);
|
||||
// Create Bar user
|
||||
DB::table('users')->insert(['name' => 'Bar', 'email' => 'bar@bar.com', 'password' => 'secret']);
|
||||
expect(DB::table('users')->get())->toHaveCount(1);
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
// Assert Bar user is not in this DB
|
||||
expect(DB::table('users')->get())->toHaveCount(1);
|
||||
expect(DB::table('users')->first()->name)->toBe('Foo');
|
||||
});
|
||||
|
||||
test('cache data is separated', function (string $store, string $bootstrapper) {
|
||||
config([
|
||||
'tenancy.bootstrappers' => [$bootstrapper],
|
||||
'tenancy.cache.stores' => [$store],
|
||||
'cache.default' => $store,
|
||||
]);
|
||||
|
||||
if ($store === 'database') {
|
||||
config([
|
||||
'cache.stores.database.connection' => 'central',
|
||||
'cache.stores.database.lock_connection' => 'central',
|
||||
]);
|
||||
|
||||
Schema::create('cache', function (Blueprint $table) {
|
||||
$table->string('key')->primary();
|
||||
$table->mediumText('value');
|
||||
$table->integer('expiration');
|
||||
});
|
||||
|
||||
Schema::create('cache_locks', function (Blueprint $table) {
|
||||
$table->string('key')->primary();
|
||||
$table->string('owner');
|
||||
$table->integer('expiration');
|
||||
});
|
||||
}
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
cache()->set('foo', 'central');
|
||||
expect(Cache::get('foo'))->toBe('central');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
// Assert central cache doesn't leak to tenant context
|
||||
expect(Cache::has('foo'))->toBeFalse();
|
||||
|
||||
cache()->set('foo', 'bar');
|
||||
expect(Cache::get('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
// Assert one tenant's data doesn't leak to another tenant
|
||||
expect(Cache::has('foo'))->toBeFalse();
|
||||
|
||||
cache()->set('foo', 'xyz');
|
||||
expect(Cache::get('foo'))->toBe('xyz');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
// Assert data didn't leak to original tenant
|
||||
expect(Cache::get('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
// Assert central is still the same
|
||||
expect(Cache::get('foo'))->toBe('central');
|
||||
})->with([
|
||||
['redis', CacheTagsBootstrapper::class],
|
||||
['memcached', CacheTagsBootstrapper::class],
|
||||
|
||||
['file', FilesystemTenancyBootstrapper::class],
|
||||
|
||||
['redis', CacheTenancyBootstrapper::class],
|
||||
['apc', CacheTenancyBootstrapper::class],
|
||||
['memcached', CacheTenancyBootstrapper::class],
|
||||
['database', CacheTenancyBootstrapper::class],
|
||||
['dynamodb', CacheTenancyBootstrapper::class],
|
||||
]);
|
||||
|
||||
test('redis data is separated', function () {
|
||||
config(['tenancy.bootstrappers' => [
|
||||
RedisTenancyBootstrapper::class,
|
||||
]]);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
Redis::set('foo', 'bar');
|
||||
expect(Redis::get('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
expect(Redis::get('foo'))->toBe(null);
|
||||
Redis::set('foo', 'xyz');
|
||||
Redis::set('abc', 'def');
|
||||
expect(Redis::get('foo'))->toBe('xyz');
|
||||
expect(Redis::get('abc'))->toBe('def');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(Redis::get('foo'))->toBe('bar');
|
||||
expect(Redis::get('abc'))->toBe(null);
|
||||
|
||||
$tenant3 = Tenant::create();
|
||||
tenancy()->initialize($tenant3);
|
||||
expect(Redis::get('foo'))->toBe(null);
|
||||
expect(Redis::get('abc'))->toBe(null);
|
||||
});
|
||||
|
||||
test('filesystem data is separated', function () {
|
||||
config([
|
||||
'tenancy.bootstrappers' => [FilesystemTenancyBootstrapper::class],
|
||||
'session.driver' => 'file',
|
||||
'cache.default' => 'file',
|
||||
'tenancy.cache.stores' => ['file'],
|
||||
]);
|
||||
|
||||
$old_storage_path = storage_path();
|
||||
$old_storage_facade_roots = [];
|
||||
foreach (config('tenancy.filesystem.disks') as $disk) {
|
||||
$old_storage_facade_roots[$disk] = config("filesystems.disks.{$disk}.root");
|
||||
}
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
Storage::disk('public')->put('foo', 'bar');
|
||||
expect(Storage::disk('public')->get('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
expect(Storage::disk('public')->exists('foo'))->toBeFalse();
|
||||
Storage::disk('public')->put('foo', 'xyz');
|
||||
Storage::disk('public')->put('abc', 'def');
|
||||
expect(Storage::disk('public')->get('foo'))->toBe('xyz');
|
||||
expect(Storage::disk('public')->get('abc'))->toBe('def');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(Storage::disk('public')->get('foo'))->toBe('bar');
|
||||
expect(Storage::disk('public')->exists('abc'))->toBeFalse();
|
||||
|
||||
$tenant3 = Tenant::create();
|
||||
tenancy()->initialize($tenant3);
|
||||
expect(Storage::disk('public')->exists('foo'))->toBeFalse();
|
||||
expect(Storage::disk('public')->exists('abc'))->toBeFalse();
|
||||
|
||||
$expected_storage_path = $old_storage_path . '/tenant' . tenant('id'); // /tenant = suffix base
|
||||
|
||||
// Check that disk prefixes respect the root_override logic
|
||||
expect(getDiskPrefix('local'))->toBe($expected_storage_path . '/app/');
|
||||
expect(getDiskPrefix('public'))->toBe($expected_storage_path . '/app/public/');
|
||||
pest()->assertSame('tenant' . tenant('id') . '/', getDiskPrefix('s3'), '/');
|
||||
|
||||
// Check suffixing logic
|
||||
$new_storage_path = storage_path();
|
||||
expect($new_storage_path)->toEqual($expected_storage_path);
|
||||
|
||||
// Check cache path
|
||||
$cachePath = cache()->store()->getStore()->getDirectory();
|
||||
expect($cachePath)
|
||||
->toBe(config('cache.stores.file.path'))
|
||||
->toBe(storage_path('framework/cache/data'));
|
||||
expect($cachePath)->toContain(tenant('id'));
|
||||
|
||||
// Check session path
|
||||
$sessionPath = invade(app('session')->driver()->getHandler())->path;
|
||||
expect($sessionPath)
|
||||
->toBe(config('session.files'))
|
||||
->toBe(storage_path('framework/sessions'));
|
||||
expect($sessionPath)->toContain(tenant('id'));
|
||||
|
||||
// URL generation is tested separately in FilesystemTenancyBootstrapperTest
|
||||
});
|
||||
|
||||
function getDiskPrefix(string $disk): string
|
||||
{
|
||||
/** @var FilesystemAdapter $disk */
|
||||
$disk = Storage::disk($disk);
|
||||
$adapter = $disk->getAdapter();
|
||||
$prefix = invade(invade($adapter)->prefixer)->prefix;
|
||||
|
||||
return $prefix;
|
||||
}
|
||||
142
tests/Bootstrappers/BroadcastChannelPrefixBootstrapperTest.php
Normal file
142
tests/Bootstrappers/BroadcastChannelPrefixBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Broadcasting\BroadcastManager;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\BroadcastChannelPrefixBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Tests\Etc\TestingBroadcaster;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
|
||||
Event::listen(
|
||||
TenantCreated::class,
|
||||
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener()
|
||||
);
|
||||
});
|
||||
|
||||
test('BroadcastChannelPrefixBootstrapper prefixes the channels events are broadcast on while tenancy is initialized', function() {
|
||||
config([
|
||||
'broadcasting.default' => $driver = 'testing',
|
||||
'broadcasting.connections.testing.driver' => $driver,
|
||||
]);
|
||||
|
||||
// Use custom broadcaster
|
||||
app(BroadcastManager::class)->extend($driver, fn () => new TestingBroadcaster('original broadcaster'));
|
||||
|
||||
config(['tenancy.bootstrappers' => [BroadcastChannelPrefixBootstrapper::class, DatabaseTenancyBootstrapper::class]]);
|
||||
|
||||
Schema::create('users', function (Blueprint $table) {
|
||||
$table->increments('id');
|
||||
$table->string('name');
|
||||
$table->string('email')->unique();
|
||||
$table->string('password');
|
||||
$table->rememberToken();
|
||||
$table->timestamps();
|
||||
});
|
||||
|
||||
universal_channel('users.{userId}', function ($user, $userId) {
|
||||
return User::find($userId)->is($user);
|
||||
});
|
||||
|
||||
$broadcaster = app(BroadcastManager::class)->driver();
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
pest()->artisan('tenants:migrate');
|
||||
|
||||
// Set up the 'testing' broadcaster override
|
||||
// Identical to the default Pusher override (BroadcastChannelPrefixBootstrapper::pusher())
|
||||
// Except for the parent class (TestingBroadcaster instead of PusherBroadcaster)
|
||||
BroadcastChannelPrefixBootstrapper::$broadcasterOverrides['testing'] = function (BroadcastManager $broadcastManager) {
|
||||
$broadcastManager->extend('testing', function ($app, $config) {
|
||||
return new class('tenant broadcaster') extends TestingBroadcaster {
|
||||
protected function formatChannels(array $channels)
|
||||
{
|
||||
$formatChannel = function (string $channel) {
|
||||
$prefixes = ['private-', 'presence-'];
|
||||
$defaultPrefix = '';
|
||||
|
||||
foreach ($prefixes as $prefix) {
|
||||
if (str($channel)->startsWith($prefix)) {
|
||||
$defaultPrefix = $prefix;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip prefixing channels flagged with the global channel prefix
|
||||
if (! str($channel)->startsWith('global__')) {
|
||||
$channel = str($channel)->after($defaultPrefix)->prepend($defaultPrefix . tenant()->getTenantKey() . '.');
|
||||
}
|
||||
|
||||
return (string) $channel;
|
||||
};
|
||||
|
||||
return array_map($formatChannel, parent::formatChannels($channels));
|
||||
}
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
auth()->login($user = User::create(['name' => 'central', 'email' => 'test@central.cz', 'password' => 'test']));
|
||||
|
||||
// The channel names used for testing the formatChannels() method (not real channels)
|
||||
$channelNames = [
|
||||
'channel',
|
||||
'global__channel', // Channels prefixed with 'global__' shouldn't get prefixed with the tenant key
|
||||
'private-user.' . $user->id,
|
||||
];
|
||||
|
||||
// formatChannels doesn't prefix the channel names until tenancy is initialized
|
||||
expect(invade(app(BroadcastManager::class)->driver())->formatChannels($channelNames))->toEqual($channelNames);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$tenantBroadcaster = app(BroadcastManager::class)->driver();
|
||||
|
||||
auth()->login($tenantUser = User::create(['name' => 'tenant', 'email' => 'test@tenant.cz', 'password' => 'test']));
|
||||
|
||||
// The current (tenant) broadcaster isn't the same as the central one
|
||||
expect($tenantBroadcaster->message)->not()->toBe($broadcaster->message);
|
||||
// Tenant broadcaster has the same channels as the central broadcaster
|
||||
expect($tenantBroadcaster->getChannels())->toEqualCanonicalizing($broadcaster->getChannels());
|
||||
// formatChannels prefixes the channel names now
|
||||
expect(invade($tenantBroadcaster)->formatChannels($channelNames))->toEqualCanonicalizing([
|
||||
'global__channel',
|
||||
$tenant->getTenantKey() . '.channel',
|
||||
'private-' . $tenant->getTenantKey() . '.user.' . $tenantUser->id,
|
||||
]);
|
||||
|
||||
// Initialize another tenant
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
auth()->login($tenantUser = User::create(['name' => 'tenant', 'email' => 'test2@tenant.cz', 'password' => 'test']));
|
||||
|
||||
// formatChannels prefixes channels with the second tenant's key now
|
||||
expect(invade(app(BroadcastManager::class)->driver())->formatChannels($channelNames))->toEqualCanonicalizing([
|
||||
'global__channel',
|
||||
$tenant2->getTenantKey() . '.channel',
|
||||
'private-' . $tenant2->getTenantKey() . '.user.' . $tenantUser->id,
|
||||
]);
|
||||
|
||||
// The bootstrapper reverts to the tenant context – the channel names won't be prefixed anymore
|
||||
tenancy()->end();
|
||||
|
||||
// The current broadcaster is the same as the central one again
|
||||
expect(app(BroadcastManager::class)->driver())->toBe($broadcaster);
|
||||
expect(invade(app(BroadcastManager::class)->driver())->formatChannels($channelNames))->toEqual($channelNames);
|
||||
});
|
||||
|
||||
105
tests/Bootstrappers/BroadcastingConfigBootstrapperTest.php
Normal file
105
tests/Bootstrappers/BroadcastingConfigBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Broadcasting\BroadcastManager;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Bootstrappers\BroadcastingConfigBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Overrides\TenancyBroadcastManager;
|
||||
use Stancl\Tenancy\Tests\Etc\TestingBroadcaster;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
|
||||
BroadcastingConfigBootstrapper::$credentialsMap = [];
|
||||
TenancyBroadcastManager::$tenantBroadcasters = ['pusher', 'ably'];
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
BroadcastingConfigBootstrapper::$credentialsMap = [];
|
||||
TenancyBroadcastManager::$tenantBroadcasters = ['pusher', 'ably'];
|
||||
});
|
||||
|
||||
test('BroadcastingConfigBootstrapper binds TenancyBroadcastManager to BroadcastManager and reverts the binding when tenancy is ended', function() {
|
||||
config(['tenancy.bootstrappers' => [BroadcastingConfigBootstrapper::class]]);
|
||||
|
||||
expect(app(BroadcastManager::class))->toBeInstanceOf(BroadcastManager::class);
|
||||
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
expect(app(BroadcastManager::class))->toBeInstanceOf(TenancyBroadcastManager::class);
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(app(BroadcastManager::class))->toBeInstanceOf(BroadcastManager::class);
|
||||
});
|
||||
|
||||
test('BroadcastingConfigBootstrapper maps tenant broadcaster credentials to config as specified in the $credentialsMap property and reverts the config after ending tenancy', function() {
|
||||
config([
|
||||
'broadcasting.connections.testing.driver' => 'testing',
|
||||
'broadcasting.connections.testing.message' => $defaultMessage = 'default',
|
||||
'tenancy.bootstrappers' => [BroadcastingConfigBootstrapper::class],
|
||||
]);
|
||||
|
||||
BroadcastingConfigBootstrapper::$credentialsMap = [
|
||||
'broadcasting.connections.testing.message' => 'testing_broadcaster_message',
|
||||
];
|
||||
|
||||
$tenant = Tenant::create(['testing_broadcaster_message' => $tenantMessage = 'first testing']);
|
||||
$tenant2 = Tenant::create(['testing_broadcaster_message' => $secondTenantMessage = 'second testing']);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect(array_key_exists('testing_broadcaster_message', tenant()->getAttributes()))->toBeTrue();
|
||||
expect(config('broadcasting.connections.testing.message'))->toBe($tenantMessage);
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(config('broadcasting.connections.testing.message'))->toBe($secondTenantMessage);
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(config('broadcasting.connections.testing.message'))->toBe($defaultMessage);
|
||||
});
|
||||
|
||||
test('BroadcastingConfigBootstrapper makes the app use broadcasters with the correct credentials', function() {
|
||||
config([
|
||||
'broadcasting.default' => 'testing',
|
||||
'broadcasting.connections.testing.driver' => 'testing',
|
||||
'broadcasting.connections.testing.message' => $defaultMessage = 'default',
|
||||
'tenancy.bootstrappers' => [BroadcastingConfigBootstrapper::class],
|
||||
]);
|
||||
|
||||
TenancyBroadcastManager::$tenantBroadcasters[] = 'testing';
|
||||
BroadcastingConfigBootstrapper::$credentialsMap = [
|
||||
'broadcasting.connections.testing.message' => 'testing_broadcaster_message',
|
||||
];
|
||||
|
||||
$registerTestingBroadcaster = fn() => app(BroadcastManager::class)->extend('testing', fn ($app, $config) => new TestingBroadcaster($config['message']));
|
||||
|
||||
$registerTestingBroadcaster();
|
||||
|
||||
expect(invade(app(BroadcastManager::class)->driver())->message)->toBe($defaultMessage);
|
||||
|
||||
$tenant = Tenant::create(['testing_broadcaster_message' => $tenantMessage = 'first testing']);
|
||||
$tenant2 = Tenant::create(['testing_broadcaster_message' => $secondTenantMessage = 'second testing']);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
$registerTestingBroadcaster();
|
||||
|
||||
expect(invade(app(BroadcastManager::class)->driver())->message)->toBe($tenantMessage);
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
$registerTestingBroadcaster();
|
||||
|
||||
expect(invade(app(BroadcastManager::class)->driver())->message)->toBe($secondTenantMessage);
|
||||
|
||||
tenancy()->end();
|
||||
$registerTestingBroadcaster();
|
||||
|
||||
expect(invade(app(BroadcastManager::class)->driver())->message)->toBe($defaultMessage);
|
||||
});
|
||||
|
||||
112
tests/Bootstrappers/CacheTagsBootstrapperTest.php
Normal file
112
tests/Bootstrappers/CacheTagsBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTagsBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
config(['tenancy.bootstrappers' => [CacheTagsBootstrapper::class]]);
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('default tag is automatically applied', function () {
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
pest()->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames());
|
||||
});
|
||||
|
||||
test('tags are merged when array is passed', function () {
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar'];
|
||||
expect(cache()->tags(['foo', 'bar'])->getTags()->getNames())->toEqual($expected);
|
||||
});
|
||||
|
||||
test('tags are merged when string is passed', function () {
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo'];
|
||||
expect(cache()->tags('foo')->getTags()->getNames())->toEqual($expected);
|
||||
});
|
||||
|
||||
test('exception is thrown when zero arguments are passed to tags method', function () {
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
pest()->expectException(\Exception::class);
|
||||
cache()->tags();
|
||||
});
|
||||
|
||||
test('exception is thrown when more than one argument is passed to tags method', function () {
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
pest()->expectException(\Exception::class);
|
||||
cache()->tags(1, 2);
|
||||
});
|
||||
|
||||
test('tags separate cache properly', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache()->put('foo', 'bar', 1);
|
||||
expect(cache()->get('foo'))->toBe('bar');
|
||||
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(cache('foo'))->not()->toBe('bar');
|
||||
|
||||
cache()->put('foo', 'xyz', 1);
|
||||
expect(cache()->get('foo'))->toBe('xyz');
|
||||
});
|
||||
|
||||
test('invoking the cache helper works', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache(['foo' => 'bar'], 1);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(cache('foo'))->not()->toBe('bar');
|
||||
|
||||
cache(['foo' => 'xyz'], 1);
|
||||
expect(cache('foo'))->toBe('xyz');
|
||||
});
|
||||
|
||||
test('cache is persisted', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache(['foo' => 'bar'], 10);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
});
|
||||
|
||||
test('cache is persisted when reidentification is used', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache(['foo' => 'bar'], 10);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
tenancy()->end();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
});
|
||||
296
tests/Bootstrappers/CacheTenancyBootstrapperTest.php
Normal file
296
tests/Bootstrappers/CacheTenancyBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,296 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Cache\CacheManager;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Tests\Etc\CacheService;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
use Stancl\Tenancy\Tests\Etc\SpecificCacheStoreService;
|
||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||
|
||||
beforeEach(function () {
|
||||
config([
|
||||
'tenancy.bootstrappers' => [
|
||||
CacheTenancyBootstrapper::class
|
||||
],
|
||||
'cache.default' => 'redis',
|
||||
'cache.stores.redis2' => config('cache.stores.redis'),
|
||||
'tenancy.cache.stores' => ['redis', 'redis2'],
|
||||
]);
|
||||
|
||||
CacheTenancyBootstrapper::$prefixGenerator = null;
|
||||
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
CacheTenancyBootstrapper::$prefixGenerator = null;
|
||||
});
|
||||
|
||||
test('correct cache prefix is used in all contexts', function () {
|
||||
$originalPrefix = config('cache.prefix');
|
||||
$prefixFormat = config('tenancy.cache.prefix');
|
||||
$getDefaultPrefixForTenant = fn (Tenant $tenant) => $originalPrefix . str($prefixFormat)->replace('%tenant%', $tenant->getTenantKey())->toString();
|
||||
$bootstrapper = app(CacheTenancyBootstrapper::class);
|
||||
|
||||
$expectCachePrefixToBe = function (string $prefix) {
|
||||
expect($prefix)
|
||||
->toBe(app('cache')->getPrefix())
|
||||
->toBe(app('cache.store')->getPrefix())
|
||||
->toBe(cache()->getPrefix())
|
||||
->toBe(cache()->store('redis2')->getPrefix());
|
||||
};
|
||||
|
||||
$expectCachePrefixToBe($originalPrefix);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
cache()->set('key', 'tenantone-value');
|
||||
$tenantOnePrefix = $getDefaultPrefixForTenant($tenant1);
|
||||
$expectCachePrefixToBe($tenantOnePrefix);
|
||||
expect($bootstrapper->generatePrefix($tenant1, 'redis'))->toBe($tenantOnePrefix);
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
cache()->set('key', 'tenanttwo-value');
|
||||
$tenantTwoPrefix = $getDefaultPrefixForTenant($tenant2);
|
||||
$expectCachePrefixToBe($tenantTwoPrefix);
|
||||
expect($bootstrapper->generatePrefix($tenant2, 'redis'))->toBe($tenantTwoPrefix);
|
||||
|
||||
// Prefix gets reverted to default after ending tenancy
|
||||
tenancy()->end();
|
||||
$expectCachePrefixToBe($originalPrefix);
|
||||
|
||||
// Assert tenant's data is accessible using the prefix from the central context
|
||||
config(['cache.prefix' => null]); // stop prefixing cache keys in central so we can provide prefix manually
|
||||
app('cache')->forgetDriver(config('cache.default'));
|
||||
|
||||
expect(cache($tenantOnePrefix . 'key'))->toBe('tenantone-value');
|
||||
expect(cache($tenantTwoPrefix . 'key'))->toBe('tenanttwo-value');
|
||||
});
|
||||
|
||||
test('cache is persisted when reidentification is used', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache(['foo' => 'bar']);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
expect(cache('foo'))->toBeNull();
|
||||
tenancy()->end();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(cache('foo'))->toBe('bar');
|
||||
});
|
||||
|
||||
test('prefixing separates the cache', function () {
|
||||
$tenant1 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
cache()->put('foo', 'bar');
|
||||
expect(cache()->get('foo'))->toBe('bar');
|
||||
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(cache()->get('foo'))->toBeNull();
|
||||
|
||||
cache()->put('foo', 'xyz');
|
||||
expect(cache()->get('foo'))->toBe('xyz');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(cache()->get('foo'))->toBe('bar');
|
||||
});
|
||||
|
||||
test('central cache is persisted', function () {
|
||||
cache()->put('key', 'central');
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
expect(cache('key'))->toBeNull();
|
||||
cache()->put('key', 'tenant');
|
||||
|
||||
expect(cache()->get('key'))->toBe('tenant');
|
||||
|
||||
tenancy()->end();
|
||||
cache()->put('key2', 'central-two');
|
||||
|
||||
expect(cache()->get('key'))->toBe('central');
|
||||
expect(cache()->get('key2'))->toBe('central-two');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
expect(cache()->get('key'))->toBe('tenant');
|
||||
expect(cache()->get('key2'))->toBeNull();
|
||||
});
|
||||
|
||||
test('only the stores specified in the config get prefixed', function () {
|
||||
// Make sure the currently used store ('redis') is the only store in the config
|
||||
// This means that the 'redis2' store won't be prefixed
|
||||
config(['tenancy.cache.stores' => ['redis']]);
|
||||
|
||||
cache()->store('redis')->put('key', 'central');
|
||||
expect(cache()->store('redis')->get('key'))->toBe('central');
|
||||
// same values -- the stores use the same connection, with the same prefix here
|
||||
expect(cache()->store('redis2')->get('key'))->toBe('central');
|
||||
|
||||
$tenant = Tenant::create();
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// now the 'redis' store is prefixed, but 'redis2' isn't
|
||||
expect(cache()->store('redis2')->get('key'))->toBe('central');
|
||||
expect(cache()->store('redis')->get('key'))->toBe(null); // central value not leaked to tenant context
|
||||
|
||||
cache()->store('redis')->put('key', 'tenant'); // change the value of the prefixed store
|
||||
expect(cache()->store('redis')->get('key'))->toBe('tenant'); // prefixed store
|
||||
|
||||
tenancy()->end();
|
||||
// still central
|
||||
expect(cache()->store('redis2')->get('key'))->toBe('central');
|
||||
expect(cache()->store('redis')->get('key'))->toBe('central');
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
expect(cache()->store('redis2')->get('key'))->toBe('central'); // still central
|
||||
expect(cache()->store('redis')->get('key'))->toBe('tenant');
|
||||
cache()->store('redis2')->put('key', 'foo'); // override non-prefixed store value
|
||||
cache()->store('redis')->put('key', 'tenant'); // the connection with the prefix still retains the tenant value
|
||||
|
||||
tenancy()->end();
|
||||
// both redis2 and redis should now be 'foo' since they got overridden previously
|
||||
expect(cache()->store('redis2')->get('key'))->toBe('foo');
|
||||
expect(cache()->store('redis')->get('key'))->toBe('foo');
|
||||
});
|
||||
|
||||
test('non default stores get prefixed too when specified in the config', function () {
|
||||
config([
|
||||
'cache.default' => 'redis',
|
||||
'tenancy.cache.stores' => ['redis', 'redis2'],
|
||||
]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$defaultPrefix = cache()->store()->getPrefix();
|
||||
$bootstrapper = app(CacheTenancyBootstrapper::class);
|
||||
|
||||
expect(cache()->store('redis')->getPrefix())->toBe($defaultPrefix);
|
||||
expect(cache()->store('redis2')->getPrefix())->toBe($defaultPrefix);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect($bootstrapper->generatePrefix($tenant, 'redis2'))
|
||||
->toBe(cache()->getPrefix())
|
||||
->toBe(cache()->store('redis2')->getPrefix()); // Non-default store
|
||||
|
||||
tenancy()->end();
|
||||
});
|
||||
|
||||
test('cache base prefix is customizable', function () {
|
||||
config([
|
||||
'tenancy.cache.prefix' => 'custom_%tenant%_'
|
||||
]);
|
||||
|
||||
$originalPrefix = config('cache.prefix');
|
||||
$tenant1 = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
expect($originalPrefix . 'custom_' . $tenant1->getTenantKey() . '_')
|
||||
->toBe(cache()->getPrefix())
|
||||
->toBe(cache()->store('redis2')->getPrefix())
|
||||
->toBe(app('cache')->getPrefix())
|
||||
->toBe(app('cache.store')->getPrefix());
|
||||
});
|
||||
|
||||
test('cache store prefix generation can be customized', function() {
|
||||
// Use custom prefix generator
|
||||
CacheTenancyBootstrapper::generatePrefixUsing($customPrefixGenerator = function (Tenant $tenant) {
|
||||
return 'redis_tenant_cache_' . $tenant->getTenantKey();
|
||||
});
|
||||
|
||||
expect(CacheTenancyBootstrapper::$prefixGenerator)->toBe($customPrefixGenerator);
|
||||
expect(app(CacheTenancyBootstrapper::class)->generatePrefix($tenant = Tenant::create(), 'redis'))
|
||||
->toBe($customPrefixGenerator($tenant));
|
||||
|
||||
tenancy()->initialize($tenant = Tenant::create());
|
||||
|
||||
// Expect the 'redis' store to use the prefix generated by the custom generator
|
||||
expect($customPrefixGenerator($tenant))
|
||||
->toBe(cache()->getPrefix())
|
||||
->toBe(cache()->store('redis2')->getPrefix())
|
||||
->toBe(app('cache')->getPrefix())
|
||||
->toBe(app('cache.store')->getPrefix());
|
||||
|
||||
tenancy()->end();
|
||||
});
|
||||
|
||||
test('cache is prefixed correctly when using a repository injected in a singleton', function () {
|
||||
$this->app->singleton(CacheService::class);
|
||||
|
||||
expect(cache('key'))->toBeNull();
|
||||
|
||||
$this->app->make(CacheService::class)->handle();
|
||||
|
||||
expect(cache('key'))->toBe('central-value');
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
expect(cache('key'))->toBeNull();
|
||||
$this->app->make(CacheService::class)->handle();
|
||||
expect(cache('key'))->toBe($tenant1->getTenantKey());
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(cache('key'))->toBeNull();
|
||||
$this->app->make(CacheService::class)->handle();
|
||||
expect(cache('key'))->toBe($tenant2->getTenantKey());
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(cache('key'))->toBe('central-value');
|
||||
});
|
||||
|
||||
test('specific central cache store can be used inside a service', function () {
|
||||
// Make sure 'redis' (the default store) is the only prefixed store
|
||||
config(['tenancy.cache.stores' => ['redis']]);
|
||||
// Name of the non-default, central cache store that we'll use using cache()->store($cacheStore)
|
||||
$cacheStore = 'redis2';
|
||||
|
||||
// Service uses the 'redis2' store which is central/not prefixed (not present in tenancy.cache.stores config)
|
||||
// The service's handle() method sets the value of the cache key 'key' to the current tenant key
|
||||
// Or to 'central-value' if tenancy isn't initialized
|
||||
$this->app->singleton(SpecificCacheStoreService::class, function() use ($cacheStore) {
|
||||
return new SpecificCacheStoreService($this->app->make(CacheManager::class), $cacheStore);
|
||||
});
|
||||
|
||||
$this->app->make(SpecificCacheStoreService::class)->handle();
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe('central-value');
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
// The store isn't prefixed, so the cache isn't separated – the values persist from one context to another
|
||||
// Also assert that the value of 'key' is set correctly inside SpecificCacheStoreService according to the current context
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe('central-value');
|
||||
$this->app->make(SpecificCacheStoreService::class)->handle();
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe($tenant1->getTenantKey());
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe($tenant1->getTenantKey());
|
||||
$this->app->make(SpecificCacheStoreService::class)->handle();
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe($tenant2->getTenantKey());
|
||||
|
||||
tenancy()->end();
|
||||
// We last executed handle() in tenant2's context, so the value should persist as tenant2's id
|
||||
expect(cache()->store($cacheStore)->get('key'))->toBe($tenant2->getTenantKey());
|
||||
});
|
||||
145
tests/Bootstrappers/DatabaseSessionBootstrapperTest.php
Normal file
145
tests/Bootstrappers/DatabaseSessionBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseSessionBootstrapper;
|
||||
use Stancl\Tenancy\Events;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||
use Stancl\Tenancy\Listeners;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||
|
||||
/**
|
||||
* This collection of regression tests verifies that SessionTenancyBootstrapper
|
||||
* fully fixes the issue described here https://github.com/archtechx/tenancy/issues/547
|
||||
*
|
||||
* This means: using the DB session driver and:
|
||||
* 1) switching to the central context from tenant requests, OR
|
||||
* 2) switching to the tenant context from central requests
|
||||
*/
|
||||
|
||||
beforeEach(function () {
|
||||
config(['session.driver' => 'database']);
|
||||
config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]);
|
||||
|
||||
Event::listen(
|
||||
TenantCreated::class,
|
||||
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener()
|
||||
);
|
||||
|
||||
Event::listen(Events\TenancyInitialized::class, Listeners\BootstrapTenancy::class);
|
||||
Event::listen(Events\TenancyEnded::class, Listeners\RevertToCentralContext::class);
|
||||
|
||||
// Sessions table for central database
|
||||
pest()->artisan('migrate', [
|
||||
'--path' => __DIR__ . '/../Etc/session_migrations',
|
||||
'--realpath' => true,
|
||||
])->assertExitCode(0);
|
||||
});
|
||||
|
||||
test('central helper can be used in tenant requests', function (bool $enabled, bool $shouldThrow) {
|
||||
if ($enabled) {
|
||||
config()->set(
|
||||
'tenancy.bootstrappers',
|
||||
array_merge(config('tenancy.bootstrappers'), [DatabaseSessionBootstrapper::class]),
|
||||
);
|
||||
}
|
||||
|
||||
$tenant = Tenant::create();
|
||||
|
||||
$tenant->domains()->create(['domain' => 'foo.localhost']);
|
||||
|
||||
// run for tenants
|
||||
pest()->artisan('tenants:migrate', [
|
||||
'--path' => __DIR__ . '/../Etc/session_migrations',
|
||||
'--realpath' => true,
|
||||
])->assertExitCode(0);
|
||||
|
||||
Route::middleware(['web', InitializeTenancyByDomain::class])->get('/bar', function () {
|
||||
session(['message' => 'tenant session']);
|
||||
|
||||
tenancy()->central(function () {
|
||||
return 'central results';
|
||||
});
|
||||
|
||||
return session('message');
|
||||
});
|
||||
|
||||
// We initialize tenancy before making the request, since sessions work a bit differently in tests
|
||||
// and we need the DB session handler to use the tenant connection (as it does in a real app on tenant requests).
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
try {
|
||||
$this->withoutExceptionHandling()
|
||||
->get('http://foo.localhost/bar')
|
||||
->assertOk()
|
||||
->assertSee('tenant session');
|
||||
|
||||
if ($shouldThrow) {
|
||||
pest()->fail('Exception not thrown');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
if ($shouldThrow) {
|
||||
pest()->assertTrue(true); // empty assertion to make the test pass
|
||||
} else {
|
||||
pest()->fail('Exception thrown: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
})->with([
|
||||
['enabled' => false, 'shouldThrow' => true],
|
||||
['enabled' => true, 'shouldThrow' => false],
|
||||
]);
|
||||
|
||||
test('tenant run helper can be used on central requests', function (bool $enabled, bool $shouldThrow) {
|
||||
if ($enabled) {
|
||||
config()->set(
|
||||
'tenancy.bootstrappers',
|
||||
array_merge(config('tenancy.bootstrappers'), [DatabaseSessionBootstrapper::class]),
|
||||
);
|
||||
}
|
||||
|
||||
Tenant::create();
|
||||
|
||||
// run for tenants
|
||||
pest()->artisan('tenants:migrate', [
|
||||
'--path' => __DIR__ . '/../Etc/session_migrations',
|
||||
'--realpath' => true,
|
||||
])->assertExitCode(0);
|
||||
|
||||
Route::middleware(['web'])->get('/bar', function () {
|
||||
session(['message' => 'central session']);
|
||||
|
||||
Tenant::first()->run(function () {
|
||||
return 'tenant results';
|
||||
});
|
||||
|
||||
return session('message');
|
||||
});
|
||||
|
||||
try {
|
||||
$this->withoutExceptionHandling()
|
||||
->get('http://localhost/bar')
|
||||
->assertOk()
|
||||
->assertSee('central session');
|
||||
|
||||
if ($shouldThrow) {
|
||||
pest()->fail('Exception not thrown');
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
if ($shouldThrow) {
|
||||
pest()->assertTrue(true); // empty assertion to make the test pass
|
||||
} else {
|
||||
pest()->fail('Exception thrown: ' . $e->getMessage());
|
||||
}
|
||||
}
|
||||
})->with([
|
||||
['enabled' => false, 'shouldThrow' => true],
|
||||
['enabled' => true, 'shouldThrow' => false],
|
||||
]);
|
||||
32
tests/Bootstrappers/DatabaseTenancyBootstrapper.php
Normal file
32
tests/Bootstrappers/DatabaseTenancyBootstrapper.php
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('database tenancy bootstrapper throws an exception if DATABASE_URL is set', function (string|null $databaseUrl) {
|
||||
if ($databaseUrl) {
|
||||
config(['database.connections.central.url' => $databaseUrl]);
|
||||
|
||||
pest()->expectException(Exception::class);
|
||||
}
|
||||
|
||||
config(['tenancy.bootstrappers' => [DatabaseTenancyBootstrapper::class]]);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
|
||||
pest()->artisan('tenants:migrate');
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
expect(true)->toBe(true);
|
||||
})->with(['abc.us-east-1.rds.amazonaws.com', null]);
|
||||
|
||||
202
tests/Bootstrappers/FilesystemTenancyBootstrapperTest.php
Normal file
202
tests/Bootstrappers/FilesystemTenancyBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Stancl\JobPipeline\JobPipeline;
|
||||
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
|
||||
use Stancl\Tenancy\Events\DeletingTenant;
|
||||
use Stancl\Tenancy\Events\TenantCreated;
|
||||
use Stancl\Tenancy\Events\TenantDeleted;
|
||||
use Stancl\Tenancy\Jobs\CreateStorageSymlinks;
|
||||
use Stancl\Tenancy\Jobs\RemoveStorageSymlinks;
|
||||
use Stancl\Tenancy\Listeners\DeleteTenantStorage;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('local storage public urls are generated correctly', function () {
|
||||
config([
|
||||
'tenancy.bootstrappers' => [
|
||||
FilesystemTenancyBootstrapper::class,
|
||||
],
|
||||
'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/',
|
||||
'tenancy.filesystem.url_override.public' => 'public-%tenant%'
|
||||
]);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
$tenant1StorageUrl = 'http://localhost/public-' . $tenant1->getKey().'/';
|
||||
$tenant2StorageUrl = 'http://localhost/public-' . $tenant2->getKey().'/';
|
||||
|
||||
tenancy()->initialize($tenant1);
|
||||
|
||||
$this->assertEquals(
|
||||
$tenant1StorageUrl,
|
||||
Storage::disk('public')->url('')
|
||||
);
|
||||
|
||||
Storage::disk('public')->put($tenant1FileName = 'tenant1.txt', 'text');
|
||||
|
||||
$this->assertEquals(
|
||||
$tenant1StorageUrl . $tenant1FileName,
|
||||
Storage::disk('public')->url($tenant1FileName)
|
||||
);
|
||||
|
||||
tenancy()->initialize($tenant2);
|
||||
|
||||
$this->assertEquals(
|
||||
$tenant2StorageUrl,
|
||||
Storage::disk('public')->url('')
|
||||
);
|
||||
|
||||
Storage::disk('public')->put($tenant2FileName = 'tenant2.txt', 'text');
|
||||
|
||||
$this->assertEquals(
|
||||
$tenant2StorageUrl . $tenant2FileName,
|
||||
Storage::disk('public')->url($tenant2FileName)
|
||||
);
|
||||
});
|
||||
|
||||
test('files can get fetched using the storage url', function() {
|
||||
config([
|
||||
'tenancy.bootstrappers' => [
|
||||
FilesystemTenancyBootstrapper::class,
|
||||
],
|
||||
'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/',
|
||||
'tenancy.filesystem.url_override.public' => 'public-%tenant%'
|
||||
]);
|
||||
|
||||
$tenant1 = Tenant::create();
|
||||
$tenant2 = Tenant::create();
|
||||
|
||||
pest()->artisan('tenants:link');
|
||||
|
||||
// First tenant
|
||||
tenancy()->initialize($tenant1);
|
||||
Storage::disk('public')->put($tenantFileName = 'tenant1.txt', $tenantKey = $tenant1->getTenantKey());
|
||||
|
||||
$url = Storage::disk('public')->url($tenantFileName);
|
||||
$tenantDiskName = str(config('tenancy.filesystem.url_override.public'))->replace('%tenant%', $tenantKey);
|
||||
$hostname = str($url)->before($tenantDiskName);
|
||||
$parsedUrl = str($url)->after($hostname);
|
||||
|
||||
expect(file_get_contents(public_path($parsedUrl)))->toBe($tenantKey);
|
||||
|
||||
// Second tenant
|
||||
tenancy()->initialize($tenant2);
|
||||
Storage::disk('public')->put($tenantFileName = 'tenant2.txt', $tenantKey = $tenant2->getTenantKey());
|
||||
|
||||
$url = Storage::disk('public')->url($tenantFileName);
|
||||
$tenantDiskName = str(config('tenancy.filesystem.url_override.public'))->replace('%tenant%', $tenantKey);
|
||||
$hostname = str($url)->before($tenantDiskName);
|
||||
$parsedUrl = str($url)->after($hostname);
|
||||
|
||||
expect(file_get_contents(public_path($parsedUrl)))->toBe($tenantKey);
|
||||
|
||||
// Central
|
||||
tenancy()->end();
|
||||
Storage::disk('public')->put($centralFileName = 'central.txt', $centralFileContent = 'central');
|
||||
|
||||
pest()->artisan('storage:link');
|
||||
$url = Storage::disk('public')->url($centralFileName);
|
||||
|
||||
expect(file_get_contents(public_path($url)))->toBe($centralFileContent);
|
||||
});
|
||||
|
||||
test('storage_path helper does not change if suffix_storage_path is off', function() {
|
||||
$originalStoragePath = storage_path();
|
||||
|
||||
// todo@tests https://github.com/tenancy-for-laravel/v4/pull/44#issue-2228530362
|
||||
|
||||
config([
|
||||
'tenancy.bootstrappers' => [FilesystemTenancyBootstrapper::class],
|
||||
'tenancy.filesystem.suffix_storage_path' => false,
|
||||
]);
|
||||
|
||||
tenancy()->initialize(Tenant::create());
|
||||
|
||||
$this->assertEquals($originalStoragePath, storage_path());
|
||||
});
|
||||
|
||||
test('links to storage disks with a configured root are suffixed if not overridden', function() {
|
||||
config([
|
||||
'filesystems.disks.public.root' => 'http://sample-s3-url.com/my-app',
|
||||
'tenancy.bootstrappers' => [
|
||||
FilesystemTenancyBootstrapper::class,
|
||||
],
|
||||
'tenancy.filesystem.root_override.public' => null,
|
||||
'tenancy.filesystem.url_override.public' => null,
|
||||
]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
|
||||
$expectedStoragePath = storage_path() . '/tenant' . $tenant->getTenantKey(); // /tenant = suffix base
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// Check suffixing logic
|
||||
expect(storage_path())->toEqual($expectedStoragePath);
|
||||
});
|
||||
|
||||
test('create and delete storage symlinks jobs work', function() {
|
||||
Event::listen(
|
||||
TenantCreated::class,
|
||||
JobPipeline::make([CreateStorageSymlinks::class])->send(function (TenantCreated $event) {
|
||||
return $event->tenant;
|
||||
})->toListener()
|
||||
);
|
||||
|
||||
Event::listen(
|
||||
TenantDeleted::class,
|
||||
JobPipeline::make([RemoveStorageSymlinks::class])->send(function (TenantDeleted $event) {
|
||||
return $event->tenant;
|
||||
})->toListener()
|
||||
);
|
||||
|
||||
config([
|
||||
'tenancy.bootstrappers' => [
|
||||
FilesystemTenancyBootstrapper::class,
|
||||
],
|
||||
'tenancy.filesystem.suffix_base' => 'tenant-',
|
||||
'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/',
|
||||
'tenancy.filesystem.url_override.public' => 'public-%tenant%'
|
||||
]);
|
||||
|
||||
/** @var Tenant $tenant */
|
||||
$tenant = Tenant::create();
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
$tenantKey = $tenant->getTenantKey();
|
||||
|
||||
$this->assertDirectoryExists(storage_path("app/public"));
|
||||
$this->assertEquals(storage_path("app/public/"), readlink(public_path("public-$tenantKey")));
|
||||
|
||||
$tenant->delete();
|
||||
|
||||
$this->assertDirectoryDoesNotExist(public_path("public-$tenantKey"));
|
||||
});
|
||||
|
||||
test('tenant storage can get deleted after the tenant when DeletingTenant listens to DeleteTenantStorage', function() {
|
||||
Event::listen(DeletingTenant::class, DeleteTenantStorage::class);
|
||||
|
||||
tenancy()->initialize(Tenant::create());
|
||||
$tenantStoragePath = storage_path();
|
||||
|
||||
Storage::fake('test');
|
||||
|
||||
expect(File::isDirectory($tenantStoragePath))->toBeTrue();
|
||||
|
||||
Storage::put('test.txt', 'testing file');
|
||||
|
||||
tenant()->delete();
|
||||
|
||||
expect(File::isDirectory($tenantStoragePath))->toBeFalse();
|
||||
});
|
||||
76
tests/Bootstrappers/FortifyRouteBootstrapperTest.php
Normal file
76
tests/Bootstrappers/FortifyRouteBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Stancl\Tenancy\Bootstrappers\Integrations\FortifyRouteBootstrapper;
|
||||
use Stancl\Tenancy\Enums\Context;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('fortify route tenancy bootstrapper updates fortify config correctly', function() {
|
||||
config(['tenancy.bootstrappers' => [FortifyRouteBootstrapper::class]]);
|
||||
|
||||
$originalFortifyHome = config('fortify.home');
|
||||
$originalFortifyRedirects = config('fortify.redirects');
|
||||
|
||||
Route::get('/home', function () {
|
||||
return true;
|
||||
})->name($homeRouteName = 'home');
|
||||
|
||||
Route::get('/{tenant}/home', function () {
|
||||
return true;
|
||||
})->name($pathIdHomeRouteName = 'tenant.home');
|
||||
|
||||
Route::get('/welcome', function () {
|
||||
return true;
|
||||
})->name($welcomeRouteName = 'welcome');
|
||||
|
||||
Route::get('/{tenant}/welcome', function () {
|
||||
return true;
|
||||
})->name($pathIdWelcomeRouteName = 'path.welcome');
|
||||
|
||||
FortifyRouteBootstrapper::$fortifyHome = $homeRouteName;
|
||||
|
||||
// Make login redirect to the central welcome route
|
||||
FortifyRouteBootstrapper::$fortifyRedirectMap['login'] = [
|
||||
'route_name' => $welcomeRouteName,
|
||||
'context' => Context::CENTRAL,
|
||||
];
|
||||
|
||||
tenancy()->initialize($tenant = Tenant::create());
|
||||
// The bootstraper makes fortify.home always receive the tenant parameter
|
||||
expect(config('fortify.home'))->toBe('http://localhost/home?tenant=' . $tenant->getTenantKey());
|
||||
|
||||
// The login redirect route has the central context specified, so it doesn't receive the tenant parameter
|
||||
expect(config('fortify.redirects'))->toEqual(['login' => 'http://localhost/welcome']);
|
||||
|
||||
tenancy()->end();
|
||||
expect(config('fortify.home'))->toBe($originalFortifyHome);
|
||||
expect(config('fortify.redirects'))->toBe($originalFortifyRedirects);
|
||||
|
||||
// Making a route's context will pass the tenant parameter to the route
|
||||
FortifyRouteBootstrapper::$fortifyRedirectMap['login']['context'] = Context::TENANT;
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect(config('fortify.redirects'))->toEqual(['login' => 'http://localhost/welcome?tenant=' . $tenant->getTenantKey()]);
|
||||
|
||||
// Make the home and login route accept the tenant as a route parameter
|
||||
// To confirm that tenant route parameter gets filled automatically too (path identification works as well as query string)
|
||||
FortifyRouteBootstrapper::$fortifyHome = $pathIdHomeRouteName;
|
||||
FortifyRouteBootstrapper::$fortifyRedirectMap['login']['route_name'] = $pathIdWelcomeRouteName;
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect(config('fortify.home'))->toBe("http://localhost/{$tenant->getTenantKey()}/home");
|
||||
expect(config('fortify.redirects'))->toEqual(['login' => "http://localhost/{$tenant->getTenantKey()}/welcome"]);
|
||||
});
|
||||
62
tests/Bootstrappers/MailTenancyBootstrapper.php
Normal file
62
tests/Bootstrappers/MailTenancyBootstrapper.php
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Stancl\Tenancy\Bootstrappers\MailConfigBootstrapper;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
});
|
||||
|
||||
test('MailTenancyBootstrapper maps tenant mail credentials to config as specified in the $credentialsMap property and makes the mailer use tenant credentials', function() {
|
||||
MailConfigBootstrapper::$credentialsMap = [
|
||||
'mail.mailers.smtp.username' => 'smtp_username',
|
||||
'mail.mailers.smtp.password' => 'smtp_password'
|
||||
];
|
||||
|
||||
config([
|
||||
'mail.default' => 'smtp',
|
||||
'mail.mailers.smtp.username' => $defaultUsername = 'default username',
|
||||
'mail.mailers.smtp.password' => 'no password',
|
||||
'tenancy.bootstrappers' => [MailConfigBootstrapper::class],
|
||||
]);
|
||||
|
||||
$tenant = Tenant::create(['smtp_password' => $password = 'testing password']);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect(array_key_exists('smtp_password', tenant()->getAttributes()))->toBeTrue();
|
||||
expect(array_key_exists('smtp_host', tenant()->getAttributes()))->toBeFalse();
|
||||
expect(config('mail.mailers.smtp.username'))->toBe($defaultUsername);
|
||||
expect(config('mail.mailers.smtp.password'))->toBe(tenant()->smtp_password);
|
||||
|
||||
// Assert that the current mailer uses tenant's smtp_password
|
||||
assertMailerTransportUsesPassword($password);
|
||||
});
|
||||
|
||||
test('MailTenancyBootstrapper reverts the config and mailer credentials to default when tenancy ends', function() {
|
||||
MailConfigBootstrapper::$credentialsMap = ['mail.mailers.smtp.password' => 'smtp_password'];
|
||||
config([
|
||||
'mail.default' => 'smtp',
|
||||
'mail.mailers.smtp.password' => $defaultPassword = 'no password',
|
||||
'tenancy.bootstrappers' => [MailConfigBootstrapper::class],
|
||||
]);
|
||||
|
||||
tenancy()->initialize(Tenant::create(['smtp_password' => $tenantPassword = 'testing password']));
|
||||
|
||||
expect(config('mail.mailers.smtp.password'))->toBe($tenantPassword);
|
||||
|
||||
assertMailerTransportUsesPassword($tenantPassword);
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(config('mail.mailers.smtp.password'))->toBe($defaultPassword);
|
||||
|
||||
// Assert that the current mailer uses the default SMTP password
|
||||
assertMailerTransportUsesPassword($defaultPassword);
|
||||
});
|
||||
|
||||
67
tests/Bootstrappers/RootUrlBootstrapperTest.php
Normal file
67
tests/Bootstrappers/RootUrlBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Stancl\Tenancy\Bootstrappers\RootUrlBootstrapper;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
RootUrlBootstrapper::$rootUrlOverride = null;
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
RootUrlBootstrapper::$rootUrlOverride = null;
|
||||
});
|
||||
|
||||
test('root url bootstrapper overrides the root url when tenancy gets initialized and reverts the url to the central one after tenancy ends', function() {
|
||||
config(['tenancy.bootstrappers' => [RootUrlBootstrapper::class]]);
|
||||
|
||||
Route::group([
|
||||
'middleware' => InitializeTenancyBySubdomain::class,
|
||||
], function () {
|
||||
Route::get('/', function () {
|
||||
return true;
|
||||
})->name('home');
|
||||
});
|
||||
|
||||
$baseUrl = url(route('home'));
|
||||
config(['app.url' => $baseUrl]);
|
||||
|
||||
$rootUrlOverride = function (Tenant $tenant) use ($baseUrl) {
|
||||
$scheme = str($baseUrl)->before('://');
|
||||
$hostname = str($baseUrl)->after($scheme . '://');
|
||||
|
||||
return $scheme . '://' . $tenant->getTenantKey() . '.' . $hostname;
|
||||
};
|
||||
|
||||
RootUrlBootstrapper::$rootUrlOverride = $rootUrlOverride;
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$tenantUrl = $rootUrlOverride($tenant);
|
||||
|
||||
expect($tenantUrl)->not()->toBe($baseUrl);
|
||||
|
||||
expect(url(route('home')))->toBe($baseUrl);
|
||||
expect(URL::to('/'))->toBe($baseUrl);
|
||||
expect(config('app.url'))->toBe($baseUrl);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
expect(url(route('home')))->toBe($tenantUrl);
|
||||
expect(URL::to('/'))->toBe($tenantUrl);
|
||||
expect(config('app.url'))->toBe($tenantUrl);
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(url(route('home')))->toBe($baseUrl);
|
||||
expect(URL::to('/'))->toBe($baseUrl);
|
||||
expect(config('app.url'))->toBe($baseUrl);
|
||||
});
|
||||
|
||||
157
tests/Bootstrappers/UrlGeneratorBootstrapperTest.php
Normal file
157
tests/Bootstrappers/UrlGeneratorBootstrapperTest.php
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
<?php
|
||||
|
||||
use Illuminate\Routing\Exceptions\UrlGenerationException;
|
||||
use Illuminate\Routing\UrlGenerator;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Stancl\Tenancy\Bootstrappers\UrlGeneratorBootstrapper;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
|
||||
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
|
||||
use Stancl\Tenancy\Overrides\TenancyUrlGenerator;
|
||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||
use Stancl\Tenancy\Events\TenancyEnded;
|
||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||
|
||||
beforeEach(function () {
|
||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||
TenancyUrlGenerator::$prefixRouteNames = false;
|
||||
TenancyUrlGenerator::$passTenantParameterToRoutes = true;
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
TenancyUrlGenerator::$prefixRouteNames = false;
|
||||
TenancyUrlGenerator::$passTenantParameterToRoutes = true;
|
||||
});
|
||||
|
||||
test('url generator bootstrapper swaps the url generator instance correctly', function() {
|
||||
config(['tenancy.bootstrappers' => [UrlGeneratorBootstrapper::class]]);
|
||||
|
||||
tenancy()->initialize(Tenant::create());
|
||||
expect(app('url'))->toBeInstanceOf(TenancyUrlGenerator::class);
|
||||
expect(url())->toBeInstanceOf(TenancyUrlGenerator::class);
|
||||
|
||||
tenancy()->end();
|
||||
expect(app('url'))->toBeInstanceOf(UrlGenerator::class)
|
||||
->not()->toBeInstanceOf(TenancyUrlGenerator::class);
|
||||
expect(url())->toBeInstanceOf(UrlGenerator::class)
|
||||
->not()->toBeInstanceOf(TenancyUrlGenerator::class);
|
||||
});
|
||||
|
||||
test('url generator bootstrapper can prefix route names passed to the route helper', function() {
|
||||
Route::get('/central/home', fn () => route('home'))->name('home');
|
||||
// Tenant route name prefix is 'tenant.' by default
|
||||
Route::get('/{tenant}/home', fn () => route('tenant.home'))->name('tenant.home')->middleware(['tenant', InitializeTenancyByPath::class]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$tenantKey = $tenant->getTenantKey();
|
||||
$centralRouteUrl = route('home');
|
||||
$tenantRouteUrl = route('tenant.home', ['tenant' => $tenantKey]);
|
||||
TenancyUrlGenerator::$bypassParameter = 'bypassParameter';
|
||||
|
||||
config(['tenancy.bootstrappers' => [UrlGeneratorBootstrapper::class]]);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// Route names don't get prefixed when TenancyUrlGenerator::$prefixRouteNames is false
|
||||
expect(route('home'))->not()->toBe($centralRouteUrl);
|
||||
// When TenancyUrlGenerator::$passTenantParameterToRoutes is true (default)
|
||||
// The route helper receives the tenant parameter
|
||||
// So in order to generate central URL, we have to pass the bypass parameter
|
||||
expect(route('home', ['bypassParameter' => true]))->toBe($centralRouteUrl);
|
||||
|
||||
|
||||
TenancyUrlGenerator::$prefixRouteNames = true;
|
||||
// The $prefixRouteNames property is true
|
||||
// The route name passed to the route() helper ('home') gets prefixed prefixed with 'tenant.' automatically
|
||||
expect(route('home'))->toBe($tenantRouteUrl);
|
||||
|
||||
// The 'tenant.home' route name doesn't get prefixed because it is already prefixed with 'tenant.'
|
||||
// Also, the route receives the tenant parameter automatically
|
||||
expect(route('tenant.home'))->toBe($tenantRouteUrl);
|
||||
|
||||
// Ending tenancy reverts route() behavior changes
|
||||
tenancy()->end();
|
||||
|
||||
expect(route('home'))->toBe($centralRouteUrl);
|
||||
});
|
||||
|
||||
test('both the name prefixing and the tenant parameter logic gets skipped when bypass parameter is used', function () {
|
||||
$tenantParameterName = PathTenantResolver::tenantParameterName();
|
||||
|
||||
Route::get('/central/home', fn () => route('home'))->name('home');
|
||||
// Tenant route name prefix is 'tenant.' by default
|
||||
Route::get('/{tenant}/home', fn () => route('tenant.home'))->name('tenant.home')->middleware(['tenant', InitializeTenancyByPath::class]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$centralRouteUrl = route('home');
|
||||
$tenantRouteUrl = route('tenant.home', ['tenant' => $tenant->getTenantKey()]);
|
||||
config(['tenancy.bootstrappers' => [UrlGeneratorBootstrapper::class]]);
|
||||
|
||||
TenancyUrlGenerator::$prefixRouteNames = true;
|
||||
TenancyUrlGenerator::$bypassParameter = 'bypassParameter';
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// The $bypassParameter parameter ('central' by default) can bypass the route name prefixing
|
||||
// When the bypass parameter is true, the generated route URL points to the route named 'home'
|
||||
expect(route('home', ['bypassParameter' => true]))->toBe($centralRouteUrl)
|
||||
// Bypass parameter prevents passing the tenant parameter directly
|
||||
->not()->toContain($tenantParameterName . '=')
|
||||
// Bypass parameter gets removed from the generated URL automatically
|
||||
->not()->toContain('bypassParameter');
|
||||
|
||||
// When the bypass parameter is false, the generated route URL points to the prefixed route ('tenant.home')
|
||||
expect(route('home', ['bypassParameter' => false]))->toBe($tenantRouteUrl)
|
||||
->not()->toContain('bypassParameter');
|
||||
});
|
||||
|
||||
test('url generator bootstrapper can make route helper generate links with the tenant parameter', function() {
|
||||
Route::get('/query_string', fn () => route('query_string'))->name('query_string')->middleware(['universal', InitializeTenancyByRequestData::class]);
|
||||
Route::get('/path', fn () => route('path'))->name('path');
|
||||
Route::get('/{tenant}/path', fn () => route('tenant.path'))->name('tenant.path')->middleware([InitializeTenancyByPath::class]);
|
||||
|
||||
$tenant = Tenant::create();
|
||||
$tenantKey = $tenant->getTenantKey();
|
||||
$queryStringCentralUrl = route('query_string');
|
||||
$queryStringTenantUrl = route('query_string', ['tenant' => $tenantKey]);
|
||||
$pathCentralUrl = route('path');
|
||||
$pathTenantUrl = route('tenant.path', ['tenant' => $tenantKey]);
|
||||
|
||||
// Makes the route helper receive the tenant parameter whenever available
|
||||
// Unless the bypass parameter is true
|
||||
TenancyUrlGenerator::$passTenantParameterToRoutes = true;
|
||||
|
||||
TenancyUrlGenerator::$bypassParameter = 'bypassParameter';
|
||||
|
||||
config(['tenancy.bootstrappers' => [UrlGeneratorBootstrapper::class]]);
|
||||
|
||||
expect(route('path'))->toBe($pathCentralUrl);
|
||||
// Tenant parameter required, but not passed since tenancy wasn't initialized
|
||||
expect(fn () => route('tenant.path'))->toThrow(UrlGenerationException::class);
|
||||
|
||||
tenancy()->initialize($tenant);
|
||||
|
||||
// Tenant parameter is passed automatically
|
||||
expect(route('path'))->not()->toBe($pathCentralUrl); // Parameter added as query string – bypassParameter needed
|
||||
expect(route('path', ['bypassParameter' => true]))->toBe($pathCentralUrl);
|
||||
expect(route('tenant.path'))->toBe($pathTenantUrl);
|
||||
|
||||
expect(route('query_string'))->toBe($queryStringTenantUrl)->toContain('tenant=');
|
||||
expect(route('query_string', ['bypassParameter' => 'true']))->toBe($queryStringCentralUrl)->not()->toContain('tenant=');
|
||||
|
||||
tenancy()->end();
|
||||
|
||||
expect(route('query_string'))->toBe($queryStringCentralUrl);
|
||||
|
||||
// Tenant parameter required, but shouldn't be passed since tenancy isn't initialized
|
||||
expect(fn () => route('tenant.path'))->toThrow(UrlGenerationException::class);
|
||||
|
||||
// Route-level identification
|
||||
pest()->get("http://localhost/query_string")->assertSee($queryStringCentralUrl);
|
||||
pest()->get("http://localhost/query_string?tenant=$tenantKey")->assertSee($queryStringTenantUrl);
|
||||
pest()->get("http://localhost/path")->assertSee($pathCentralUrl);
|
||||
pest()->get("http://localhost/$tenantKey/path")->assertSee($pathTenantUrl);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue