1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 17:44:04 +00:00
tenancy/tests/CommandsTest.php
Samuel Štancl 198f34f5e1
[4.x] Add pending tenants (modified #782) (#869)
* Add readied tenants

Add config for readied tenants
Add `create` and `clear` command
Add Readied scope and static functions
Add tests

* Fix initialize function name

* Add readied events

* Fix readied column cast

* Laravel 6 compatible

* Add readied scope tests

* Rename config from include_in_scope to include_in_queries

* Change terminology to pending

* Update CreatePendingTenants.php

* Laravel 6 compatible

* Update CreatePendingTenants.php

* runForMultiple can scope pending tenants

* Fix issues

* Code and comment style improvements

* Change 'tenant' to 'tenants' in command signature

* Fix code style (php-cs-fixer)

* Rename variables in CreatePendingTenants

* Remove withPending from runForMultiple

* Update tenants option trait

* Update command that use tenants

* Fix code style (php-cs-fixer)

* Improve getTenants condition

* Update config comments

* Minor config comment corrections

* Grammar fix

* Update comments and naming

* Correct comments

* Improve writing

* Remove pending tenant clearing time constraints

* Allow using only one time constraint for clearing the pending tenants

* phpunit to pest

* Fix code style (php-cs-fixer)

* Fix code style (php-cs-fixer)

* [4.x] Optionally delete storage after tenant deletion (#938)

* Add test for deleting storage after tenant deletion

* Save `storage_path()` in a variable after initializing tenant in test

Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>

* Add DeleteTenantStorage listener

* Update test name

* Remove storage deletion config key

* Remove tenant storage deletion events

* Move tenant storage deletion to the DeletingTenant event

Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>

* [4.x] Finish incomplete and missing tests (#947)

* complete test sqlite manager customize path

* complete test seed command works

* complete uniqe exists test

* Update SingleDatabaseTenancyTest.php

* refactor the ternary into if condition

* custom path

* simplify if condition

* random dir name

* Update SingleDatabaseTenancyTest.php

* Update CommandsTest.php

* prefix random DB name with custom_

Co-authored-by: Samuel Štancl <samuel@archte.ch>

* [4.x] Add batch tenancy queue bootstrapper (#874)

* exclude master from CI

* Add batch tenancy queue bootstrapper

* add test case

* skip tests for old versions

* variable docblocks

* use Laravel's connection getter and setter

* convert test to pest

* bottom space

* singleton regis in TestCase

* Update src/Bootstrappers/BatchTenancyBootstrapper.php

Co-authored-by: Samuel Štancl <samuel@archte.ch>

* convert batch class resolution to property level

* enabled BatchTenancyBootstrapper by default

* typehint DatabaseBatchRepository

* refactore name

* DI DB manager

* typehint

* Update config.php

* use initialize() twice without end()ing tenancy to assert that previousConnection logic works correctly

Co-authored-by: Samuel Štancl <samuel.stancl@gmail.com>
Co-authored-by: Abrar Ahmad <abrar.dev99@gmail.com>
Co-authored-by: Samuel Štancl <samuel@archte.ch>

* [4.x] Storage::url() support (modified #689) (#909)

* This adds support for tenancy aware  Storage::url() method

* Trigger CI build

* Fixed Link command for Laravel v6, added StorageLink Events, more StorageLink tests, added RemoveStorageSymlinks Job, added Storage Jobs to TenancyServiceProvider stub, renamed misleading config example.

* Fix typo

* Fix code style (php-cs-fixer)

* Update config comments

* Format code in Link command, make writing more concise

* Change "symLinks" to "symlinks"

* Refactor Link command

* Fix test name typo

* Test fetching files using the public URL

* Extract Link command logic into actions

* Fix code style (php-cs-fixer)

* Check if closure is null in CreateStorageSymlinksAction

* Stop using command terminology in CreateStorageSymlinksAction

* Separate the Storage::url() test cases

* Update url_override comments

* Remove afterLink closures, add types, move actions, add usage explanation to the symlink trait

* Fix code style (php-cs-fixer)

* Update public storage URL test

* Fix issue with using str()

* Improve url_override comment, add todos

* add todo comment

* fix docblock style

* Add link command tests back

* Add types to $tenants in the action handle() methods

* Fix typo, update variable name formatting

* Add tests for the symlink actions

* Change possibleTenantSymlinks not to prefix the paths twice while tenancy is initialized

* Fix code style (php-cs-fixer)

* Stop testing storage directory existence in symlink test

* Don't specify full namespace for Tenant model annotation

* Don't specify full namespace in ActionTest

* Remove "change to DI" todo

* Remove possibleTenantSymlinks return annotation

* Remove symlink-related jobs, instantiate and use actions

* Revert "Remove symlink-related jobs, instantiate and use actions"

This reverts commit 547440c887.

* Add a comment line about the possible tenant symlinks

* Correct storagePath and publicPath variables

* Revert "Correct storagePath and publicPath variables"

This reverts commit e3aa8e2086.

* add a todo

Co-authored-by: Martin Vlcek <martin@dontfreakout.eu>
Co-authored-by: lukinovec <lukinovec@gmail.com>
Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>

* Use HasTenantOptions in Link

* Correct the tenant order in Run command

* Fix code style (php-cs-fixer)

* Fix formatting issue

* Add missing imports

* Fix code style (php-cs-fixer)

* Use HasTenantOptions instead of the old trait name in Up/Down commands

* Fix test name typo

* Remove redundant passing of $withPending to runForMultiple in TenantCollection's runForEach

* Make `with-pending` default to `config('tenancy.pending.include_in_queries')` in HasTenantOptions

* Make `createPending()` return the created tenant

* Fix code style (php-cs-fixer)

* Remove tenant ordering

* Fix code style (php-cs-fixer)

* Remove duplicate tenancy bootstrappers config setting

* Add and use getWithPendingOption method

* Fix code style (php-cs-fixer)

* Add optionNotPassedValue property

* Test using --with-pending and the include_in_queries config value

* Make with-pending VALUE_NONE

* use plural in test names

* fix test names

* add pullPendingTenantFromPool

* Add docblock type

* Import commands

* Fix code style (php-cs-fixer)

* Move pending tenant tests to a more appropriate file

* Delete queuetest from gitignore

* Delete queuetest file

* Add queuetest to gitignore

* Rename pullPendingTenant to pullPending and don't pass bool to that method

* Add a test that checks if pulling a pending tenant removes it from the pool

* bump stancl/virtualcolumn to ^1.3

* Update pending tenant pulling test

* Dynamically get columns for pending queries

* Dynamically get virtual column name in ClearPendingTenants

* Fix ClearPendingTenants bug

* Make test name more accurate

* Update test name

* add a todo

* Update include in queries test name

* Remove `Tenant::query()->delete()` from pending tenant check test

* Rename the pending tenant check test name

* Update HasPending.php

* fix all() call

* code style

* all() -> get()

* Remove redundant `Tenant::all()` call

Co-authored-by: j.stein <joristein@gmail.com>
Co-authored-by: lukinovec <lukinovec@gmail.com>
Co-authored-by: PHP CS Fixer <phpcsfixer@example.com>
Co-authored-by: Abrar Ahmad <abrar.dev99@gmail.com>
Co-authored-by: Riley19280 <rileyaven88@gmail.com>
Co-authored-by: Martin Vlcek <martin@dontfreakout.eu>
2022-10-31 12:14:44 +01:00

380 lines
13 KiB
PHP

<?php
declare(strict_types=1);
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\Support\Facades\Schema;
use Stancl\Tenancy\Jobs\DeleteDomains;
use Illuminate\Support\Facades\Artisan;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Jobs\DeleteDatabase;
use Illuminate\Database\DatabaseManager;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Events\TenantDeleted;
use Stancl\Tenancy\Tests\Etc\TestSeeder;
use Stancl\Tenancy\Events\DeletingTenant;
use Stancl\Tenancy\Tests\Etc\ExampleSeeder;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
beforeEach(function () {
if (file_exists($schemaPath = database_path('schema/tenant-schema.dump'))) {
unlink($schemaPath);
}
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());
config([
'tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class,
],
'tenancy.filesystem.suffix_base' => 'tenant-',
'tenancy.filesystem.root_override.public' => '%storage_path%/app/public/',
'tenancy.filesystem.url_override.public' => 'public-%tenant_id%'
]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
});
afterEach(function () {
// Cleanup tenancy config cache
if (file_exists(base_path('config/tenancy.php'))) {
unlink(base_path('config/tenancy.php'));
}
});
test('migrate command doesnt change the db connection', function () {
expect(Schema::hasTable('users'))->toBeFalse();
$old_connection_name = app(DatabaseManager::class)->connection()->getName();
Artisan::call('tenants:migrate');
$new_connection_name = app(DatabaseManager::class)->connection()->getName();
expect(Schema::hasTable('users'))->toBeFalse();
expect($new_connection_name)->toEqual($old_connection_name);
pest()->assertNotEquals('tenant', $new_connection_name);
});
test('migrate command works without options', function () {
$tenant = Tenant::create();
expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate');
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
expect(Schema::hasTable('users'))->toBeTrue();
});
test('migrate command works with tenants option', function () {
$tenant = Tenant::create();
Artisan::call('tenants:migrate', [
'--tenants' => [$tenant['id']],
]);
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize(Tenant::create());
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
expect(Schema::hasTable('users'))->toBeTrue();
});
test('migrate command loads schema state', function () {
$tenant = Tenant::create();
expect(Schema::hasTable('schema_users'))->toBeFalse();
expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate --schema-path="tests/Etc/tenant-schema.dump"');
expect(Schema::hasTable('schema_users'))->toBeFalse();
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
// Check for both tables to see if missing migrations also get executed
expect(Schema::hasTable('schema_users'))->toBeTrue();
expect(Schema::hasTable('users'))->toBeTrue();
});
test('dump command works', function () {
$tenant = Tenant::create();
Artisan::call('tenants:migrate');
tenancy()->initialize($tenant);
Artisan::call('tenants:dump --path="tests/Etc/tenant-schema-test.dump"');
expect('tests/Etc/tenant-schema-test.dump')->toBeFile();
});
test('tenant dump file gets created as tenant-schema.dump in the database schema folder by default', function() {
config(['tenancy.migration_parameters.--schema-path' => $schemaPath = database_path('schema/tenant-schema.dump')]);
$tenant = Tenant::create();
Artisan::call('tenants:migrate');
tenancy()->initialize($tenant);
Artisan::call('tenants:dump');
expect($schemaPath)->toBeFile();
});
test('migrate command uses the correct schema path by default', function () {
config(['tenancy.migration_parameters.--schema-path' => 'tests/Etc/tenant-schema.dump']);
$tenant = Tenant::create();
expect(Schema::hasTable('schema_users'))->toBeFalse();
expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate');
expect(Schema::hasTable('schema_users'))->toBeFalse();
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
// Check for both tables to see if missing migrations also get executed
expect(Schema::hasTable('schema_users'))->toBeTrue();
expect(Schema::hasTable('users'))->toBeTrue();
});
test('rollback command works', function () {
$tenant = Tenant::create();
Artisan::call('tenants:migrate');
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
expect(Schema::hasTable('users'))->toBeTrue();
Artisan::call('tenants:rollback');
expect(Schema::hasTable('users'))->toBeFalse();
});
test('seed command works', function (){
$tenant = Tenant::create();
Artisan::call('tenants:migrate');
$tenant->run(function (){
expect(DB::table('users')->count())->toBe(0);
});
Artisan::call('tenants:seed', ['--class' => TestSeeder::class]);
$tenant->run(function (){
$user = DB::table('users');
expect($user->count())->toBe(1)
->and($user->first()->email)->toBe('seeded@user');
});
});
test('database connection is switched to default', function () {
databaseConnectionSwitchedToDefault();
});
test('database connection is switched to default when tenancy has been initialized', function () {
tenancy()->initialize(Tenant::create());
databaseConnectionSwitchedToDefault();
});
test('run command works', function () {
runCommandWorks();
});
test('install command works', function () {
if (! is_dir($dir = app_path('Http'))) {
mkdir($dir, 0777, true);
}
if (! is_dir($dir = base_path('routes'))) {
mkdir($dir, 0777, true);
}
pest()->artisan('tenancy:install')
->expectsConfirmation('Would you like to show your support by starring the project on GitHub?', 'no')
->assertExitCode(0);
expect(base_path('routes/tenant.php'))->toBeFile();
expect(base_path('config/tenancy.php'))->toBeFile();
expect(app_path('Providers/TenancyServiceProvider.php'))->toBeFile();
expect(database_path('migrations/2019_09_15_000010_create_tenants_table.php'))->toBeFile();
expect(database_path('migrations/2019_09_15_000020_create_domains_table.php'))->toBeFile();
expect(database_path('migrations/tenant'))->toBeDirectory();
});
test('migrate fresh command works', function () {
$tenant = Tenant::create();
expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate-fresh');
expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant);
expect(Schema::hasTable('users'))->toBeTrue();
expect(DB::table('users')->exists())->toBeFalse();
DB::table('users')->insert(['name' => 'xxx', 'password' => bcrypt('password'), 'email' => 'foo@bar.xxx']);
expect(DB::table('users')->exists())->toBeTrue();
// test that db is wiped
Artisan::call('tenants:migrate-fresh');
expect(DB::table('users')->exists())->toBeFalse();
});
test('run command with array of tenants works', function () {
$tenantId1 = Tenant::create()->getTenantKey();
$tenantId2 = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate-fresh');
pest()->artisan("tenants:run --tenants=$tenantId1 --tenants=$tenantId2 'foo foo --b=bar --c=xyz'")
->expectsOutputToContain('Tenant: ' . $tenantId1)
->expectsOutputToContain('Tenant: ' . $tenantId2)
->assertExitCode(0);
});
test('link command works', function() {
$tenantId1 = Tenant::create()->getTenantKey();
$tenantId2 = Tenant::create()->getTenantKey();
pest()->artisan('tenants:link')
->assertExitCode(0);
$this->assertDirectoryExists(storage_path("tenant-$tenantId1/app/public"));
$this->assertEquals(storage_path("tenant-$tenantId1/app/public/"), readlink(public_path("public-$tenantId1")));
$this->assertDirectoryExists(storage_path("tenant-$tenantId2/app/public"));
$this->assertEquals(storage_path("tenant-$tenantId2/app/public/"), readlink(public_path("public-$tenantId2")));
pest()->artisan('tenants:link', [
'--remove' => true,
])->assertExitCode(0);
$this->assertDirectoryDoesNotExist(public_path("public-$tenantId1"));
$this->assertDirectoryDoesNotExist(public_path("public-$tenantId2"));
});
test('link command works with a specified tenant', function() {
$tenantKey = Tenant::create()->getTenantKey();
pest()->artisan('tenants:link', [
'--tenants' => [$tenantKey],
]);
$this->assertDirectoryExists(storage_path("tenant-$tenantKey/app/public"));
$this->assertEquals(storage_path("tenant-$tenantKey/app/public/"), readlink(public_path("public-$tenantKey")));
pest()->artisan('tenants:link', [
'--remove' => true,
'--tenants' => [$tenantKey],
]);
$this->assertDirectoryDoesNotExist(public_path("public-$tenantKey"));
});
test('run command works when sub command asks questions and accepts arguments', function () {
$tenant = Tenant::create();
$id = $tenant->getTenantKey();
Artisan::call('tenants:migrate');
pest()->artisan("tenants:run --tenants=$id 'user:addwithname Abrar' ")
->expectsQuestion('What is your email?', 'email@localhost')
->expectsOutputToContain("Tenant: $id.")
->expectsOutput("User created: Abrar(email@localhost)")
->assertExitCode(0);
// Assert we are in central context
expect(tenancy()->initialized)->toBeFalse();
// Assert user was created in tenant context
tenancy()->initialize($tenant);
$user = User::first();
// Assert user is same as provided using the command
expect($user->name)->toBe('Abrar');
expect($user->email)->toBe('email@localhost');
});
test('migrate fresh command only deletes tenant databases if drop_tenant_databases_on_migrate_fresh is true', function (bool $dropTenantDBsOnMigrateFresh) {
Event::listen(DeletingTenant::class,
JobPipeline::make([DeleteDomains::class])->send(function (DeletingTenant $event) {
return $event->tenant;
})->shouldBeQueued(false)->toListener()
);
Event::listen(
TenantDeleted::class,
JobPipeline::make([DeleteDatabase::class])->send(function (TenantDeleted $event) {
return $event->tenant;
})->shouldBeQueued(false)->toListener()
);
config(['tenancy.database.drop_tenant_databases_on_migrate_fresh' => $dropTenantDBsOnMigrateFresh]);
$shouldHaveDBAfterMigrateFresh = ! $dropTenantDBsOnMigrateFresh;
/** @var Tenant[] $tenants */
$tenants = [
Tenant::create(),
Tenant::create(),
Tenant::create(),
];
$tenantHasDatabase = fn (Tenant $tenant) => $tenant->database()->manager()->databaseExists($tenant->database()->getName());
foreach ($tenants as $tenant) {
expect($tenantHasDatabase($tenant))->toBeTrue();
}
pest()->artisan('migrate:fresh', [
'--force' => true,
'--path' => __DIR__ . '/../assets/migrations',
'--realpath' => true,
]);
foreach ($tenants as $tenant) {
expect($tenantHasDatabase($tenant))->toBe($shouldHaveDBAfterMigrateFresh);
}
})->with([true, false]);
// todo@tests
function runCommandWorks(): void
{
$id = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
pest()->artisan("tenants:run --tenants=$id 'foo foo --b=bar --c=xyz' ")
->expectsOutput("User's name is Test command")
->expectsOutput('foo')
->expectsOutput('xyz');
}
// todo@tests
function databaseConnectionSwitchedToDefault()
{
$originalDBName = DB::connection()->getDatabaseName();
Artisan::call('tenants:migrate');
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
Artisan::call('tenants:seed', ['--class' => ExampleSeeder::class]);
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
Artisan::call('tenants:rollback');
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
runCommandWorks();
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
}