1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 12:54:05 +00:00

merge 3.x

This commit is contained in:
Samuel Štancl 2022-06-01 14:58:44 +02:00
commit eca7b336bc
30 changed files with 524 additions and 147 deletions

View file

@ -4,23 +4,27 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Illuminate\Support\Facades\Cache;
use Illuminate\Filesystem\FilesystemAdapter;
use ReflectionObject;
use ReflectionProperty;
use Illuminate\Support\Str;
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\Storage;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
class BootstrapperTest extends TestCase
{
@ -165,6 +169,7 @@ class BootstrapperTest extends TestCase
$tenant2 = Tenant::create();
tenancy()->initialize($tenant1);
Storage::disk('public')->put('foo', 'bar');
$this->assertSame('bar', Storage::disk('public')->get('foo'));
@ -184,30 +189,38 @@ class BootstrapperTest extends TestCase
$this->assertFalse(Storage::disk('public')->exists('foo'));
$this->assertFalse(Storage::disk('public')->exists('abc'));
$expected_storage_path = $old_storage_path . '/tenant' . tenant('id'); // /tenant = suffix base
// Check that disk prefixes respect the root_override logic
$this->assertSame($expected_storage_path . '/app/', $this->getDiskPrefix('local'));
$this->assertSame($expected_storage_path . '/app/public/', $this->getDiskPrefix('public'));
$this->assertSame('tenant' . tenant('id') . '/', $this->getDiskPrefix('s3'), '/');
// Check suffixing logic
$new_storage_path = storage_path();
$this->assertEquals($old_storage_path . '/' . config('tenancy.filesystem.suffix_base') . tenant('id'), $new_storage_path);
$this->assertEquals($expected_storage_path, $new_storage_path);
}
foreach (config('tenancy.filesystem.disks') as $disk) {
$suffix = config('tenancy.filesystem.suffix_base') . tenant('id');
protected function getDiskPrefix(string $disk): string
{
/** @var FilesystemAdapter $disk */
$disk = Storage::disk($disk);
$adapter = $disk->getAdapter();
/** @var FilesystemAdapter $filesystemDisk */
$filesystemDisk = Storage::disk($disk);
$current_path_prefix = $filesystemDisk->getAdapter()->getPathPrefix();
if ($override = config("tenancy.filesystem.root_override.{$disk}")) {
$correct_path_prefix = str_replace('%storage_path%', storage_path(), $override);
} else {
if ($base = $old_storage_facade_roots[$disk]) {
$correct_path_prefix = $base . "/$suffix/";
} else {
$correct_path_prefix = "$suffix/";
}
}
$this->assertSame($correct_path_prefix, $current_path_prefix);
if (! Str::startsWith(app()->version(), '9.')) {
return $adapter->getPathPrefix();
}
$prefixer = (new ReflectionObject($adapter))->getProperty('prefixer');
$prefixer->setAccessible(true);
// reflection -> instance
$prefixer = $prefixer->getValue($adapter);
$prefix = (new ReflectionProperty($prefixer, 'prefix'));
$prefix->setAccessible(true);
return $prefix->getValue($prefixer);
}
// for queues see QueueTest

View file

@ -10,6 +10,7 @@ use Illuminate\Support\Str;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\Events\DatabaseCreated;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
@ -67,14 +68,18 @@ class DatabaseUsersTest extends TestCase
$this->assertTrue($manager->databaseExists($tenant->database()->getName()));
$this->expectException(TenantDatabaseUserAlreadyExistsException::class);
Event::fake([DatabaseCreated::class]);
$tenant2 = Tenant::create([
'tenancy_db_username' => $username,
]);
/** @var ManagesDatabaseUsers $manager */
$manager = $tenant2->database()->manager();
$manager2 = $tenant2->database()->manager();
// database was not created because of DB transaction
$this->assertFalse($manager->databaseExists($tenant2->database()->getName()));
$this->assertFalse($manager2->databaseExists($tenant2->database()->getName()));
Event::assertNotDispatched(DatabaseCreated::class);
}
/** @test */

View file

@ -1 +0,0 @@
{"tenant_id":"The current tenant id is: acme"}

View file

@ -4,12 +4,14 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Foundation\Http\Exceptions\MaintenanceModeException;
use Illuminate\Support\Facades\Route;
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Symfony\Component\HttpKernel\Exception\ServiceUnavailableHttpException;
class MaintenanceModeTest extends TestCase
{
@ -32,7 +34,7 @@ class MaintenanceModeTest extends TestCase
$tenant->putDownForMaintenance();
$this->expectException(MaintenanceModeException::class);
$this->expectException(HttpException::class);
$this->withoutExceptionHandling()
->get('http://acme.localhost/foo');
}

View file

@ -4,18 +4,33 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Closure;
use Exception;
use Illuminate\Support\Str;
use Illuminate\Bus\Queueable;
use Spatie\Valuestore\Valuestore;
use Illuminate\Support\Facades\DB;
use Stancl\Tenancy\Tests\Etc\User;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Support\Facades\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Schema;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Illuminate\Queue\InteractsWithQueue;
use Stancl\Tenancy\Events\TenantCreated;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\Events\JobProcessing;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Event;
use Spatie\Valuestore\Valuestore;
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
use PDO;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
class QueueTest extends TestCase
{
@ -31,13 +46,68 @@ class QueueTest extends TestCase
config([
'tenancy.bootstrappers' => [
QueueTenancyBootstrapper::class,
DatabaseTenancyBootstrapper::class,
],
'queue.default' => 'redis',
]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
$this->valuestore = Valuestore::make(__DIR__ . '/Etc/tmp/queuetest.json')->flush();
$this->createValueStore();
}
public function tearDown(): void
{
$this->valuestore->flush();
}
protected function createValueStore(): void
{
$valueStorePath = __DIR__ . '/Etc/tmp/queuetest.json';
if (! file_exists($valueStorePath)) {
// The directory sometimes goes missing as well when the file is deleted in git
if (! is_dir(__DIR__ . '/Etc/tmp')) {
mkdir(__DIR__ . '/Etc/tmp');
}
file_put_contents($valueStorePath, '');
}
$this->valuestore = Valuestore::make($valueStorePath)->flush();
}
protected function withFailedJobs()
{
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
protected function withUsers()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
protected function withTenantDatabases()
{
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());
}
/** @test */
@ -49,7 +119,7 @@ class QueueTest extends TestCase
tenancy()->initialize($tenant);
Event::fake([JobProcessing::class]);
Event::fake([JobProcessing::class, JobProcessed::class]);
dispatch(new TestJob($this->valuestore));
@ -79,21 +149,95 @@ class QueueTest extends TestCase
});
}
/** @test */
public function tenancy_is_initialized_inside_queues()
/**
* @test
*
* @testWith [true]
* [false]
*/
public function tenancy_is_initialized_inside_queues(bool $shouldEndTenancy)
{
$tenant = Tenant::create([
'id' => 'acme',
]);
$this->withTenantDatabases();
$this->withFailedJobs();
$tenant = Tenant::create();
tenancy()->initialize($tenant);
dispatch(new TestJob($this->valuestore));
$this->withUsers();
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->valuestore->put('userName', 'Bar');
dispatch(new TestJob($this->valuestore, $user));
$this->assertFalse($this->valuestore->has('tenant_id'));
if ($shouldEndTenancy) {
tenancy()->end();
}
$this->artisan('queue:work --once');
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id'));
$tenant->run(function () use ($user) {
$this->assertSame('Bar', $user->fresh()->name);
});
}
/**
* @test
*
* @testWith [true]
* [false]
*/
public function tenancy_is_initialized_when_retrying_jobs(bool $shouldEndTenancy)
{
if (! Str::startsWith(app()->version(), '8')) {
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
}
$this->withFailedJobs();
$this->withTenantDatabases();
$tenant = Tenant::create();
tenancy()->initialize($tenant);
$this->withUsers();
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->valuestore->put('userName', 'Bar');
$this->valuestore->put('shouldFail', true);
dispatch(new TestJob($this->valuestore, $user));
$this->assertFalse($this->valuestore->has('tenant_id'));
if ($shouldEndTenancy) {
tenancy()->end();
}
$this->artisan('queue:work --once');
$this->assertSame(1, DB::connection('central')->table('failed_jobs')->count());
$this->assertNull($this->valuestore->get('tenant_id')); // job failed
$this->artisan('queue:retry all');
$this->artisan('queue:work --once');
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count());
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id')); // job succeeded
$tenant->run(function () use ($user) {
$this->assertSame('Bar', $user->fresh()->name);
});
}
/** @test */
@ -127,13 +271,31 @@ class TestJob implements ShouldQueue
/** @var Valuestore */
protected $valuestore;
public function __construct(Valuestore $valuestore)
/** @var User|null */
protected $user;
public function __construct(Valuestore $valuestore, User $user = null)
{
$this->valuestore = $valuestore;
$this->user = $user;
}
public function handle()
{
if ($this->valuestore->get('shouldFail')) {
$this->valuestore->put('shouldFail', false);
throw new Exception('failing');
}
if ($this->user) {
assert($this->user->getConnectionName() === 'tenant');
}
$this->valuestore->put('tenant_id', 'The current tenant id is: ' . tenant('id'));
if ($userName = $this->valuestore->get('userName')) {
$this->user->update(['name' => $userName]);
}
}
}

View file

@ -4,17 +4,21 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use PDO;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Database\DatabaseManager;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager;
@ -102,6 +106,52 @@ class TenantDatabaseManagerTest extends TestCase
];
}
/** @test */
public function the_tenant_connection_is_fully_removed()
{
config([
'tenancy.boostrappers' => [
DatabaseTenancyBootstrapper::class,
],
]);
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);
$tenant = Tenant::create();
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
$this->assertArrayNotHasKey('tenant', config('database.connections'));
tenancy()->initialize($tenant);
$this->createUsersTable();
$this->assertSame(['central', 'tenant'], array_keys(app('db')->getConnections()));
$this->assertArrayHasKey('tenant', config('database.connections'));
tenancy()->end();
$this->assertSame(['central'], array_keys(app('db')->getConnections()));
$this->assertNull(config('database.connections.tenant'));
}
protected function createUsersTable()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/** @test */
public function db_name_is_prefixed_with_db_path_when_sqlite_is_used()
{
@ -144,7 +194,11 @@ class TenantDatabaseManagerTest extends TestCase
]);
tenancy()->initialize($tenant);
$this->assertSame($tenant->database()->getName(), config('database.connections.' . config('database.default') . '.schema'));
$schemaConfig = version_compare(app()->version(), '9.0', '>=') ?
config('database.connections.' . config('database.default') . '.search_path') :
config('database.connections.' . config('database.default') . '.schema');
$this->assertSame($tenant->database()->getName(), $schemaConfig);
$this->assertSame($originalDatabaseName, config(['database.connections.pgsql.database']));
}
@ -217,5 +271,6 @@ class TenantDatabaseManagerTest extends TestCase
/** @test */
public function path_used_by_sqlite_manager_can_be_customized()
{
$this->markTestIncomplete();
}
}

View file

@ -48,7 +48,11 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
protected function getEnvironmentSetUp($app)
{
if (file_exists(__DIR__ . '/../.env')) {
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
if (method_exists(\Dotenv\Dotenv::class, 'createImmutable')) {
\Dotenv\Dotenv::createImmutable(__DIR__ . '/..')->load();
} else {
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
}
}
$app['config']->set([
@ -83,6 +87,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
'public',
's3',
],
'filesystems.disks.s3.bucket' => 'foo',
'tenancy.redis.tenancy' => env('TENANCY_TEST_REDIS_TENANCY', true),
'database.redis.client' => env('TENANCY_TEST_REDIS_CLIENT', 'phpredis'),
'tenancy.redis.prefixed_connections' => ['default'],