From 439b5b1dc108a48a057cc6525d1746cf881f1285 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20=C5=A0tancl?= Date: Sun, 3 May 2020 04:00:34 +0200 Subject: [PATCH] Get old tests to pass --- assets/config.php | 4 +- phpunit.xml | 2 +- src/Commands/Migrate.php | 8 +++- src/Commands/MigrateFresh.php | 2 +- src/Commands/Rollback.php | 8 +++- src/Commands/Seed.php | 2 - src/DatabaseConfig.php | 30 ++++-------- src/DatabaseManager.php | 16 +++---- .../Database/DatabaseStorageDriver.php | 12 ++--- .../Database/DomainRepository.php | 4 +- src/Tenant.php | 1 + ...rmissionControlledMySQLDatabaseManager.php | 8 ++-- src/Traits/DealsWithMigrations.php | 2 +- tests/CacheManagerTest.php | 7 ++- tests/CommandsTest.php | 9 +--- tests/DataSeparationTest.php | 6 +-- tests/DatabaseManagerTest.php | 24 ++++++---- tests/DatabaseSchemaManagerTest.php | 9 ++-- tests/Etc/User.php | 8 ++++ tests/FacadeTest.php | 3 ++ tests/QueueTest.php | 3 ++ tests/ReidentificationTest.php | 2 + tests/TenancyBootstrappersTest.php | 1 + tests/TenantClassTest.php | 5 +- tests/TenantDatabaseManagerTest.php | 48 +++++++++++++++---- tests/TenantManagerTest.php | 1 + tests/TenantStorageTest.php | 3 ++ tests/TestCase.php | 26 +++++----- 28 files changed, 154 insertions(+), 100 deletions(-) create mode 100644 tests/Etc/User.php diff --git a/assets/config.php b/assets/config.php index a5d89ad8..eb24b1dc 100644 --- a/assets/config.php +++ b/assets/config.php @@ -255,8 +255,8 @@ return [ */ 'migrate_after_creation' => false, 'migration_parameters' => [ - // '--force' => true, // Set this to true to be able to run migrations in production - // '--path' => [], // If you need to customize paths to tenant migrations + '--force' => true, // Set this to true to be able to run migrations in production + // '--path' => [database_path('migrations/tenant')], // If you need to customize paths to tenant migrations ], /** diff --git a/phpunit.xml b/phpunit.xml index d4f07804..a1c16a21 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -28,7 +28,7 @@ - + diff --git a/src/Commands/Migrate.php b/src/Commands/Migrate.php index 8151ff5a..4859d047 100644 --- a/src/Commands/Migrate.php +++ b/src/Commands/Migrate.php @@ -45,6 +45,12 @@ class Migrate extends MigrateCommand */ public function handle() { + foreach (config('tenancy.migration_parameters') as $parameter => $value) { + if (! $this->input->hasParameterOption($parameter)) { + $this->input->setOption(ltrim($parameter, '-'), $value); + } + } + if (! $this->confirmToProceed()) { return; } @@ -52,8 +58,6 @@ class Migrate extends MigrateCommand tenancy()->all($this->option('tenants'))->each(function ($tenant) { $this->line("Tenant: {$tenant['id']}"); - $this->input->setOption('database', $tenant->database()->getTemplateConnectionName()); - $tenant->run(function () { // Migrate parent::handle(); diff --git a/src/Commands/MigrateFresh.php b/src/Commands/MigrateFresh.php index e08a0fa0..eb4b0f16 100644 --- a/src/Commands/MigrateFresh.php +++ b/src/Commands/MigrateFresh.php @@ -39,7 +39,7 @@ final class MigrateFresh extends Command $tenant->run(function ($tenant) { $this->info('Dropping tables.'); $this->call('db:wipe', array_filter([ - '--database' => $tenant->database()->getTemplateConnectionName(), + '--database' => 'tenant', '--force' => true, ])); diff --git a/src/Commands/Rollback.php b/src/Commands/Rollback.php index ec228412..0a85a10e 100644 --- a/src/Commands/Rollback.php +++ b/src/Commands/Rollback.php @@ -45,6 +45,12 @@ class Rollback extends RollbackCommand */ public function handle() { + foreach (config('tenancy.migration_parameters') as $parameter => $value) { + if (! $this->input->hasParameterOption($parameter)) { + $this->input->setOption(ltrim($parameter, '-'), $value); + } + } + if (! $this->confirmToProceed()) { return; } @@ -52,8 +58,6 @@ class Rollback extends RollbackCommand tenancy()->all($this->option('tenants'))->each(function ($tenant) { $this->line("Tenant: {$tenant['id']}"); - $this->input->setOption('database', $tenant->database()->getTemplateConnectionName()); - $tenant->run(function () { // Rollback parent::handle(); diff --git a/src/Commands/Seed.php b/src/Commands/Seed.php index c57c36eb..acc697e0 100644 --- a/src/Commands/Seed.php +++ b/src/Commands/Seed.php @@ -56,8 +56,6 @@ class Seed extends SeedCommand tenancy()->all($this->option('tenants'))->each(function ($tenant) { $this->line("Tenant: {$tenant['id']}"); - $this->input->setOption('database', $tenant->database()->getTemplateConnectionName()); - $tenant->run(function () { // Seed parent::handle(); diff --git a/src/DatabaseConfig.php b/src/DatabaseConfig.php index 064832ea..00dc9714 100644 --- a/src/DatabaseConfig.php +++ b/src/DatabaseConfig.php @@ -48,17 +48,17 @@ class DatabaseConfig $this->tenant = $tenant; } - public static function generateDatabaseNameUsing(callable $databaseNameGenerator): void + public static function generateDatabaseNamesUsing(callable $databaseNameGenerator): void { static::$databaseNameGenerator = $databaseNameGenerator; } - public static function generateUsernameUsing(callable $usernameGenerator): void + public static function generateUsernamesUsing(callable $usernameGenerator): void { static::$usernameGenerator = $usernameGenerator; } - public static function generatePasswordUsing(callable $passwordGenerator): void + public static function generatePasswordsUsing(callable $passwordGenerator): void { static::$passwordGenerator = $passwordGenerator; } @@ -86,25 +86,13 @@ class DatabaseConfig $this->tenant->data['_tenancy_db_username'] = $this->getUsername() ?? (static::$usernameGenerator)($this->tenant); $this->tenant->data['_tenancy_db_password'] = $this->getPassword() ?? (static::$passwordGenerator)($this->tenant); } - - $this->tenant->save(); } - /** - * Template used to construct the tenant connection. Also serves as - * the root connection on which the tenant database is created. - */ - public function getTemplateConnectionName() + public function getTemplateConnectionName(): string { - $name = $this->tenant->data['_tenancy_db_connection'] ?? 'tenant'; - - // If we're using e.g. 'tenant', the default, template connection - // and it doesn't exist, we'll go for the default DB template. - if (! array_key_exists($name, config('database.connections'))) { - $name = config('tenancy.database.template_connection') ?? DatabaseManager::$originalDefaultConnectionName; - } - - return $name; + return $this->tenant->data['_tenancy_db_connection'] + ?? config('tenancy.database.template_connection') + ?? DatabaseManager::$originalDefaultConnectionName; } /** @@ -112,7 +100,9 @@ class DatabaseConfig */ public function connection(): array { - $templateConnection = config("database.connections.{$this->getTemplateConnectionName()}"); + $template = $this->getTemplateConnectionName(); + + $templateConnection = config("database.connections.{$template}"); $databaseName = $this->getName(); if (($manager = $this->manager()) instanceof ModifiesDatabaseNameForConnection) { diff --git a/src/DatabaseManager.php b/src/DatabaseManager.php index 0b32d72c..e141fb03 100644 --- a/src/DatabaseManager.php +++ b/src/DatabaseManager.php @@ -55,8 +55,8 @@ class DatabaseManager public function connect(Tenant $tenant) { $this->createTenantConnection($tenant); - $this->setDefaultConnection($tenant->database()->getTemplateConnectionName()); - $this->switchConnection($tenant->database()->getTemplateConnectionName()); + $this->setDefaultConnection('tenant'); + $this->switchConnection('tenant'); } /** @@ -64,10 +64,11 @@ class DatabaseManager */ public function reconnect() { - // Opposite order to connect() because we don't - // want to ever purge the central connection - $this->switchConnection(static::$originalDefaultConnectionName); + if ($this->tenancy->initialized) { + $this->database->purge('tenant'); + } $this->setDefaultConnection(static::$originalDefaultConnectionName); + $this->switchConnection(static::$originalDefaultConnectionName); } /** @@ -83,7 +84,7 @@ class DatabaseManager */ public function createTenantConnection(Tenant $tenant) { - $this->app['config']["database.connections.{$tenant->database()->getTemplateConnectionName()}"] = $tenant->database()->connection(); + $this->app['config']["database.connections.tenant"] = $tenant->database()->connection(); } /** @@ -91,7 +92,6 @@ class DatabaseManager */ public function switchConnection(string $connection) { - $this->database->purge(); $this->database->reconnect($connection); $this->database->setDefaultConnection($connection); } @@ -120,8 +120,6 @@ class DatabaseManager */ public function createDatabase(Tenant $tenant, array $afterCreating = []) { - $tenant->database()->makeCredentials(); - $afterCreating = array_merge( $afterCreating, $this->tenancy->event('database.creating', $tenant->database()->getName(), $tenant) diff --git a/src/StorageDrivers/Database/DatabaseStorageDriver.php b/src/StorageDrivers/Database/DatabaseStorageDriver.php index 77a3ffdf..5381dae0 100644 --- a/src/StorageDrivers/Database/DatabaseStorageDriver.php +++ b/src/StorageDrivers/Database/DatabaseStorageDriver.php @@ -21,22 +21,22 @@ use Stancl\Tenancy\Tenant; class DatabaseStorageDriver implements StorageDriver, CanDeleteKeys, CanFindByAnyKey { /** @var Application */ - protected $app; + public $app; /** @var Connection */ - protected $centralDatabase; + public $centralDatabase; /** @var TenantRepository */ - protected $tenants; + public $tenants; /** @var DomainRepository */ - protected $domains; + public $domains; /** @var CachedTenantResolver */ - protected $cache; + public $cache; /** @var Tenant The default tenant. */ - protected $tenant; + public $tenant; public function __construct(Application $app, ConfigRepository $config, CachedTenantResolver $cache) { diff --git a/src/StorageDrivers/Database/DomainRepository.php b/src/StorageDrivers/Database/DomainRepository.php index 4e21b9ad..3e77396f 100644 --- a/src/StorageDrivers/Database/DomainRepository.php +++ b/src/StorageDrivers/Database/DomainRepository.php @@ -50,8 +50,6 @@ class DomainRepository extends Repository public function getTable(ConfigRepository $config) { - return $config->get('tenancy.storage_drivers.db.table_names.DomainModel') // legacy - ?? $config->get('tenancy.storage_drivers.db.table_names.domains') - ?? 'domains'; + return $config->get('tenancy.storage_drivers.db.table_names.domains') ?? 'domains'; } } diff --git a/src/Tenant.php b/src/Tenant.php index 86fc8688..4a9824f8 100644 --- a/src/Tenant.php +++ b/src/Tenant.php @@ -230,6 +230,7 @@ class Tenant implements ArrayAccess if ($this->persisted) { $this->manager->updateTenant($this); } else { + $this->database()->makeCredentials(); $this->manager->createTenant($this); } diff --git a/src/TenantDatabaseManagers/PermissionControlledMySQLDatabaseManager.php b/src/TenantDatabaseManagers/PermissionControlledMySQLDatabaseManager.php index 12872b73..bafcf3b8 100644 --- a/src/TenantDatabaseManagers/PermissionControlledMySQLDatabaseManager.php +++ b/src/TenantDatabaseManagers/PermissionControlledMySQLDatabaseManager.php @@ -25,12 +25,12 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl $hostname = $databaseConfig->connection()['host']; $password = $databaseConfig->getPassword(); - $this->database()->statement("CREATE USER `{$username}`@`{$hostname}` IDENTIFIED BY `{$password}`"); + $this->database()->statement("CREATE USER `{$username}`@`{$hostname}` IDENTIFIED BY '{$password}'"); $grants = implode(', ', static::$grants); if ($this->isVersion8()) { // MySQL 8+ - $grantQuery = "GRANT $grants ON `$database`.* TO `$username`@`$hostname`"; + $grantQuery = "GRANT $grants ON $database.* TO `$username`@`$hostname`"; } else { // MySQL 5.7 $grantQuery = "GRANT $grants ON $database.* TO `$username`@`$hostname` IDENTIFIED BY '$password'"; } @@ -40,13 +40,13 @@ class PermissionControlledMySQLDatabaseManager extends MySQLDatabaseManager impl protected function isVersion8(): bool { - $version = $this->database()->select($this->db->raw('select version()'))[0]->{'version()'}; + $version = $this->database()->select($this->database()->raw('select version()'))[0]->{'version()'}; return version_compare($version, '8.0.0') >= 0; } public function deleteUser(DatabaseConfig $databaseConfig): bool { - return $this->database()->statement("DROP USER IF EXISTS '{$databaseConfig->username}'"); + return $this->database()->statement("DROP USER IF EXISTS '{$databaseConfig->getUsername()}'"); } } diff --git a/src/Traits/DealsWithMigrations.php b/src/Traits/DealsWithMigrations.php index f730cf07..edbae934 100644 --- a/src/Traits/DealsWithMigrations.php +++ b/src/Traits/DealsWithMigrations.php @@ -12,6 +12,6 @@ trait DealsWithMigrations return parent::getMigrationPaths(); } - return config('tenancy.migration_paths', [config('tenancy.migrations_directory') ?? database_path('migrations/tenant')]); + return database_path('migrations/tenant'); } } diff --git a/tests/CacheManagerTest.php b/tests/CacheManagerTest.php index 77e0c357..13e88916 100644 --- a/tests/CacheManagerTest.php +++ b/tests/CacheManagerTest.php @@ -8,11 +8,10 @@ use Stancl\Tenancy\Tenant; class CacheManagerTest extends TestCase { - public $autoInitTenancy = false; - /** @test */ public function default_tag_is_automatically_applied() { + $this->createTenant(); $this->initTenancy(); $this->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames()); } @@ -20,6 +19,7 @@ class CacheManagerTest extends TestCase /** @test */ public function tags_are_merged_when_array_is_passed() { + $this->createTenant(); $this->initTenancy(); $expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar']; $this->assertEquals($expected, cache()->tags(['foo', 'bar'])->getTags()->getNames()); @@ -28,6 +28,7 @@ class CacheManagerTest extends TestCase /** @test */ public function tags_are_merged_when_string_is_passed() { + $this->createTenant(); $this->initTenancy(); $expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo']; $this->assertEquals($expected, cache()->tags('foo')->getTags()->getNames()); @@ -36,6 +37,7 @@ class CacheManagerTest extends TestCase /** @test */ public function exception_is_thrown_when_zero_arguments_are_passed_to_tags_method() { + $this->createTenant(); $this->initTenancy(); $this->expectException(\Exception::class); cache()->tags(); @@ -44,6 +46,7 @@ class CacheManagerTest extends TestCase /** @test */ public function exception_is_thrown_when_more_than_one_argument_is_passed_to_tags_method() { + $this->createTenant(); $this->initTenancy(); $this->expectException(\Exception::class); cache()->tags(1, 2); diff --git a/tests/CommandsTest.php b/tests/CommandsTest.php index 39bb46e2..e1522b1e 100644 --- a/tests/CommandsTest.php +++ b/tests/CommandsTest.php @@ -12,15 +12,9 @@ use Stancl\Tenancy\Tests\Etc\ExampleSeeder; class CommandsTest extends TestCase { + public $autoCreateTenant = true; public $autoInitTenancy = false; - public function setUp(): void - { - parent::setUp(); - - config(['tenancy.migration_paths', [database_path('../migrations')]]); - } - /** @test */ public function migrate_command_doesnt_change_the_db_connection() { @@ -173,6 +167,7 @@ class CommandsTest extends TestCase $tenant = tenancy()->all()[1]; // a tenant is autocreated prior to this $data = $tenant->data; unset($data['id']); + unset($data['_tenancy_db_name']); $this->assertSame(['plan' => 'free', 'email' => 'foo@test.local'], $data); $this->assertSame(['aaa.localhost', 'bbb.localhost'], $tenant->domains); diff --git a/tests/DataSeparationTest.php b/tests/DataSeparationTest.php index a6240d12..8fe21c66 100644 --- a/tests/DataSeparationTest.php +++ b/tests/DataSeparationTest.php @@ -10,6 +10,7 @@ use Illuminate\Support\Facades\Redis; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use Stancl\Tenancy\Tenant; +use Stancl\Tenancy\Tests\Etc\User; class DataSeparationTest extends TestCase { @@ -151,8 +152,3 @@ class DataSeparationTest extends TestCase $this->assertFalse(Storage::disk('public')->exists('abc')); } } - -class User extends \Illuminate\Database\Eloquent\Model -{ - protected $guarded = []; -} diff --git a/tests/DatabaseManagerTest.php b/tests/DatabaseManagerTest.php index 125b0d84..0d18ca76 100644 --- a/tests/DatabaseManagerTest.php +++ b/tests/DatabaseManagerTest.php @@ -5,16 +5,16 @@ declare(strict_types=1); namespace Stancl\Tenancy\Tests; use Stancl\Tenancy\DatabaseManager; +use Stancl\Tenancy\Tenant; class DatabaseManagerTest extends TestCase { - public $autoInitTenancy = false; - /** @test */ public function reconnect_method_works() { $old_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName(); - tenancy()->init('test.localhost'); + $this->createTenant(); + $this->initTenancy(); app(\Stancl\Tenancy\DatabaseManager::class)->reconnect(); $new_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName(); @@ -25,22 +25,30 @@ class DatabaseManagerTest extends TestCase /** @test */ public function db_name_is_prefixed_with_db_path_when_sqlite_is_used() { + if (file_exists(database_path('foodb'))) { + unlink(database_path('foodb')); // cleanup + } config(['database.connections.fooconn.driver' => 'sqlite']); - app(DatabaseManager::class)->createTenantConnection('foodb', 'fooconn'); + $tenant = Tenant::new()->withData([ + '_tenancy_db_name' => 'foodb', + '_tenancy_db_connection' => 'fooconn', + ])->save(); + app(DatabaseManager::class)->createTenantConnection($tenant); - $this->assertSame(config('database.connections.fooconn.database'), database_path('foodb')); + $this->assertSame(config('database.connections.tenant.database'), database_path('foodb')); } /** @test */ public function the_default_db_is_used_when_template_connection_is_null() { - $this->assertSame('sqlite', config('database.default')); + $this->assertSame('central', config('database.default')); config([ - 'database.connections.sqlite.foo' => 'bar', + 'database.connections.central.foo' => 'bar', 'tenancy.database.template_connection' => null, ]); - tenancy()->init('test.localhost'); + $this->createTenant(); + $this->initTenancy(); $this->assertSame('tenant', config('database.default')); $this->assertSame('bar', config('database.connections.' . config('database.default') . '.foo')); diff --git a/tests/DatabaseSchemaManagerTest.php b/tests/DatabaseSchemaManagerTest.php index e2ed64a7..e79eeb31 100644 --- a/tests/DatabaseSchemaManagerTest.php +++ b/tests/DatabaseSchemaManagerTest.php @@ -4,11 +4,14 @@ declare(strict_types=1); namespace Stancl\Tenancy\Tests; +use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Str; use Stancl\Tenancy\Tenant; +use Stancl\Tenancy\Tests\Etc\User; class DatabaseSchemaManagerTest extends TestCase { + public $autoCreateTenant = true; public $autoInitTenancy = false; protected function getEnvironmentSetUp($app) @@ -17,6 +20,7 @@ class DatabaseSchemaManagerTest extends TestCase $app['config']->set([ 'database.default' => 'pgsql', + 'tenancy.storage_drivers.db.connection' => 'pgsql', 'database.connections.pgsql.database' => 'main', 'database.connections.pgsql.schema' => 'public', 'tenancy.database.template_connection' => null, @@ -42,8 +46,6 @@ class DatabaseSchemaManagerTest extends TestCase /** @test */ public function the_default_db_is_used_when_template_connection_is_null() { - config(['database.default' => 'pgsql']); - $this->assertSame('pgsql', config('database.default')); config([ 'database.connections.pgsql.foo' => 'bar', @@ -53,7 +55,7 @@ class DatabaseSchemaManagerTest extends TestCase tenancy()->init('test.localhost'); $this->assertSame('tenant', config('database.default')); - $this->assertSame('bar', config('database.connections.' . config('database.default') . '.foo')); + $this->assertSame('bar', config('database.connections.tenant.foo')); } /** @test */ @@ -95,6 +97,7 @@ class DatabaseSchemaManagerTest extends TestCase $tenant1 = Tenant::create('tenant1.localhost'); $tenant2 = Tenant::create('tenant2.localhost'); + \Artisan::call('tenants:migrate', [ '--tenants' => [$tenant1['id'], $tenant2['id']], ]); diff --git a/tests/Etc/User.php b/tests/Etc/User.php new file mode 100644 index 00000000..0c791c98 --- /dev/null +++ b/tests/Etc/User.php @@ -0,0 +1,8 @@ + $id]); $tenant->foo = 'bar'; $tenant->save(); - $this->assertEquals(['id' => $id, 'foo' => 'bar'], $tenant->data); - $this->assertEquals(['id' => $id, 'foo' => 'bar'], tenancy()->find($id)->data); + $this->assertEquals(['id' => $id, 'foo' => 'bar', '_tenancy_db_name' => $tenant->database()->getName()], $tenant->data); + $this->assertEquals(['id' => $id, 'foo' => 'bar', '_tenancy_db_name' => $tenant->database()->getName()], tenancy()->find($id)->data); $tenant->addDomains('abc.localhost'); $tenant->save(); @@ -102,6 +102,7 @@ class TenantClassTest extends TestCase $data = tenancy()->all()->first()->data; unset($data['id']); + unset($data['_tenancy_db_name']); $this->assertSame(['foo' => 'bar'], $data); } diff --git a/tests/TenantDatabaseManagerTest.php b/tests/TenantDatabaseManagerTest.php index 7445374e..7c4ff514 100644 --- a/tests/TenantDatabaseManagerTest.php +++ b/tests/TenantDatabaseManagerTest.php @@ -28,25 +28,46 @@ class TenantDatabaseManagerTest extends TestCase $this->markTestSkipped('As to not bloat your computer with test databases, this test is not run by default.'); } + config()->set([ + "tenancy.database_managers.$driver" => $databaseManager, + ]); + $name = 'db' . $this->randomString(); + $tenant = Tenant::new()->withData([ + '_tenancy_db_name' => $name, + '_tenancy_db_connection' => $driver, + ]); + $this->assertFalse(app($databaseManager)->databaseExists($name)); - app($databaseManager)->createDatabase($name); + $tenant->save(); // generate credentials & create DB $this->assertTrue(app($databaseManager)->databaseExists($name)); - app($databaseManager)->deleteDatabase($name); + app($databaseManager)->deleteDatabase($tenant); $this->assertFalse(app($databaseManager)->databaseExists($name)); } /** @test */ public function dbs_can_be_created_when_another_driver_is_used_for_the_central_db() { - $this->assertSame('sqlite', config('database.default')); + $this->assertSame('central', config('database.default')); $database = 'db' . $this->randomString(); - app(MySQLDatabaseManager::class)->createDatabase($database); + $tenant = Tenant::new()->withData([ + '_tenancy_db_name' => $database, + '_tenancy_db_connection' => 'mysql', + ]); + + $this->assertFalse(app(MySQLDatabaseManager::class)->databaseExists($database)); + $tenant->save(); // create DB $this->assertTrue(app(MySQLDatabaseManager::class)->databaseExists($database)); - $database = 'db2' . $this->randomString(); - app(PostgreSQLDatabaseManager::class)->createDatabase($database); + $database = 'db' . $this->randomString(); + $tenant = Tenant::new()->withData([ + '_tenancy_db_name' => $database, + '_tenancy_db_connection' => 'pgsql', + ]); + + $this->assertFalse(app(PostgreSQLDatabaseManager::class)->databaseExists($database)); + $tenant->save(); // create DB $this->assertTrue(app(PostgreSQLDatabaseManager::class)->databaseExists($database)); } @@ -60,16 +81,25 @@ class TenantDatabaseManagerTest extends TestCase $this->markTestSkipped('As to not bloat your computer with test databases, this test is not run by default.'); } - config()->set('database.default', $driver); + config()->set([ + 'database.default' => $driver, + "tenancy.database_managers.$driver" => $databaseManager, + ]); $name = 'db' . $this->randomString(); + $tenant = Tenant::new()->withData([ + '_tenancy_db_name' => $name, + '_tenancy_db_connection' => $driver, + ]); + $tenant->database()->makeCredentials(); + $this->assertFalse(app($databaseManager)->databaseExists($name)); - $job = new QueuedTenantDatabaseCreator(app($databaseManager), $name); + $job = new QueuedTenantDatabaseCreator(app($databaseManager), $tenant); $job->handle(); $this->assertTrue(app($databaseManager)->databaseExists($name)); - $job = new QueuedTenantDatabaseDeleter(app($databaseManager), $name); + $job = new QueuedTenantDatabaseDeleter(app($databaseManager), $tenant); $job->handle(); $this->assertFalse(app($databaseManager)->databaseExists($name)); } diff --git a/tests/TenantManagerTest.php b/tests/TenantManagerTest.php index b4bb6e1d..3198123b 100644 --- a/tests/TenantManagerTest.php +++ b/tests/TenantManagerTest.php @@ -167,6 +167,7 @@ class TenantManagerTest extends TestCase $tenant_data = $tenant->data; unset($tenant_data['id']); + unset($tenant_data['_tenancy_db_name']); $this->assertSame($data, $tenant_data); } diff --git a/tests/TenantStorageTest.php b/tests/TenantStorageTest.php index 568746cb..65354129 100644 --- a/tests/TenantStorageTest.php +++ b/tests/TenantStorageTest.php @@ -9,6 +9,9 @@ use Stancl\Tenancy\Tenant; class TenantStorageTest extends TestCase { + public $autoCreateTenant = true; + public $autoInitTenancy = true; + /** @test */ public function deleting_a_tenant_works() { diff --git a/tests/TestCase.php b/tests/TestCase.php index a753e321..59d584bc 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -9,8 +9,8 @@ use Stancl\Tenancy\Tenant; abstract class TestCase extends \Orchestra\Testbench\TestCase { - public $autoCreateTenant = true; - public $autoInitTenancy = true; + public $autoCreateTenant = false; + public $autoInitTenancy = false; /** * Setup the test environment. @@ -24,12 +24,12 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase Redis::connection('tenancy')->flushdb(); Redis::connection('cache')->flushdb(); - $originalConnection = config('database.default'); - $this->loadMigrationsFrom([ - '--path' => realpath(__DIR__ . '/../assets/migrations'), - '--database' => 'central', + file_put_contents(database_path('central.sqlite'), ''); + $this->artisan('migrate:fresh', [ + '--force' => true, + '--path' => __DIR__ . '/../assets/migrations', + '--realpath' => true, ]); - config(['database.default' => $originalConnection]); // fix issue caused by loadMigrationsFrom if ($this->autoCreateTenant) { $this->createTenant(); @@ -62,9 +62,8 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase \Dotenv\Dotenv::create(__DIR__ . '/..')->load(); } - fclose(fopen(database_path('central.sqlite'), 'w')); - $app['config']->set([ + 'database.default' => 'central', 'database.redis.cache.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'), 'database.redis.default.host' => env('TENANCY_TEST_REDIS_HOST', '127.0.0.1'), 'database.redis.options.prefix' => 'foo', @@ -80,9 +79,10 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase 'database.connections.central' => [ 'driver' => 'sqlite', 'database' => database_path('central.sqlite'), + // 'database' => ':memory:', ], 'tenancy.database' => [ - 'template_connection' => 'sqlite', + 'template_connection' => 'central', 'prefix' => 'tenant', 'suffix' => '.sqlite', ], @@ -97,7 +97,11 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase 'tenancy.redis.tenancy' => env('TENANCY_TEST_REDIS_TENANCY', true), 'database.redis.client' => env('TENANCY_TEST_REDIS_CLIENT', 'phpredis'), 'tenancy.redis.prefixed_connections' => ['default'], - 'tenancy.migration_paths' => [database_path('../migrations')], + 'tenancy.migration_parameters' => [ + '--path' => [database_path('../migrations')], + '--realpath' => true, + '--force' => true, + ], 'tenancy.storage_drivers.db.connection' => 'central', 'tenancy.bootstrappers.redis' => \Stancl\Tenancy\TenancyBootstrappers\RedisTenancyBootstrapper::class, 'queue.connections.central' => [