mirror of
https://github.com/archtechx/tenancy.git
synced 2025-12-12 15:34:03 +00:00
[4.x] Migrate tests to Pest (#884)
* Add Pest dependencies * Add base Pest file * Convert test cases * Remove non-compound imports * Adopt expectation API * Optimize uses * Shift cleanup * phpunit -> pest * Fix tests in PR #884 PHPUnit to Pest Converter (#885) * fixed tests, remove method duplications, restore necessary inner classes * Update CommandsTest.php * temporary checks run on `shift-64622` on branch. * fixed `TestSeeder` class not resolved * fixed messed up names * removed `uses` from individual files and add it in `Pest` * extract tests to helpers * use pest dataset * Update AutomaticModeTest.php * newline * todo convention * resolve reviews * added `// todo@tests` * remove shift branch from CI workflow Co-authored-by: Samuel Štancl <samuel@archte.ch> * check if I have write permission * Convert newly added tests to Pest Co-authored-by: Shift <shift@laravelshift.com> Co-authored-by: Abrar Ahmad <abrar.dev99@gmail.com>
This commit is contained in:
parent
69de181b7d
commit
b47c5549ef
32 changed files with 3010 additions and 3478 deletions
|
|
@ -1,7 +1,12 @@
|
||||||
{
|
{
|
||||||
"name": "stancl/tenancy",
|
"name": "stancl/tenancy",
|
||||||
"description": "Automatic multi-tenancy for your Laravel application.",
|
"description": "Automatic multi-tenancy for your Laravel application.",
|
||||||
"keywords": ["laravel", "multi-tenancy", "multi-database", "tenancy"],
|
"keywords": [
|
||||||
|
"laravel",
|
||||||
|
"multi-tenancy",
|
||||||
|
"multi-database",
|
||||||
|
"tenancy"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"authors": [
|
"authors": [
|
||||||
{
|
{
|
||||||
|
|
@ -20,10 +25,10 @@
|
||||||
"require-dev": {
|
"require-dev": {
|
||||||
"laravel/framework": "^6.0|^7.0|^8.0|^9.0",
|
"laravel/framework": "^6.0|^7.0|^8.0|^9.0",
|
||||||
"orchestra/testbench": "^4.0|^5.0|^6.0|^7.0",
|
"orchestra/testbench": "^4.0|^5.0|^6.0|^7.0",
|
||||||
"phpunit/phpunit": "*",
|
|
||||||
"league/flysystem-aws-s3-v3": "^1.0|^3.0",
|
"league/flysystem-aws-s3-v3": "^1.0|^3.0",
|
||||||
"doctrine/dbal": "^2.10",
|
"doctrine/dbal": "^2.10",
|
||||||
"spatie/valuestore": "^1.2.5"
|
"spatie/valuestore": "^1.2.5",
|
||||||
|
"pestphp/pest": "^1.21"
|
||||||
},
|
},
|
||||||
"autoload": {
|
"autoload": {
|
||||||
"psr-4": {
|
"psr-4": {
|
||||||
|
|
|
||||||
2
test
2
test
|
|
@ -1,3 +1,3 @@
|
||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
docker-compose exec -T test vendor/bin/phpunit "$@"
|
docker-compose exec -T test vendor/bin/pest "$@"
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
use Stancl\Tenancy\Contracts\TenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Events\TenancyEnded;
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
|
|
@ -12,113 +10,99 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class AutomaticModeTest extends TestCase
|
beforeEach(function () {
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('context is switched when tenancy is initialized', function () {
|
||||||
|
contextIsSwitchedWhenTenancyInitialized();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('context is reverted when tenancy is ended', function () {
|
||||||
|
contextIsSwitchedWhenTenancyInitialized();
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
expect(app('tenancy_ended'))->toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('context is switched when tenancy is reinitialized', function () {
|
||||||
|
config(['tenancy.bootstrappers' => [
|
||||||
|
MyBootstrapper::class,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(app('tenancy_initialized_for_tenant'))->toBe('acme');
|
||||||
|
|
||||||
|
$tenant2 = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant2);
|
||||||
|
|
||||||
|
expect(app('tenancy_initialized_for_tenant'))->toBe('foobar');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('central helper runs callbacks in the central state', function () {
|
||||||
|
tenancy()->initialize($tenant = Tenant::create());
|
||||||
|
|
||||||
|
tenancy()->central(function () {
|
||||||
|
expect(tenant())->toBe(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(tenant())->toBe($tenant);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('central helper returns the value from the callback', function () {
|
||||||
|
tenancy()->initialize(Tenant::create());
|
||||||
|
|
||||||
|
$this->assertSame('foo', tenancy()->central(function () {
|
||||||
|
return 'foo';
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('central helper reverts back to tenant context', function () {
|
||||||
|
tenancy()->initialize($tenant = Tenant::create());
|
||||||
|
|
||||||
|
tenancy()->central(function () {
|
||||||
|
//
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(tenant())->toBe($tenant);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('central helper doesnt change tenancy state when called in central context', function () {
|
||||||
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
expect(tenant())->toBeNull();
|
||||||
|
|
||||||
|
tenancy()->central(function () {
|
||||||
|
//
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
expect(tenant())->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo@tests
|
||||||
|
function contextIsSwitchedWhenTenancyInitialized()
|
||||||
{
|
{
|
||||||
public function setUp(): void
|
config(['tenancy.bootstrappers' => [
|
||||||
{
|
MyBootstrapper::class,
|
||||||
parent::setUp();
|
]]);
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
$tenant = Tenant::create([
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
'id' => 'acme',
|
||||||
}
|
]);
|
||||||
|
|
||||||
/** @test */
|
tenancy()->initialize($tenant);
|
||||||
public function context_is_switched_when_tenancy_is_initialized()
|
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
MyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
expect(app('tenancy_initialized_for_tenant'))->toBe('acme');
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame('acme', app('tenancy_initialized_for_tenant'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function context_is_reverted_when_tenancy_is_ended()
|
|
||||||
{
|
|
||||||
$this->context_is_switched_when_tenancy_is_initialized();
|
|
||||||
|
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
$this->assertSame(true, app('tenancy_ended'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function context_is_switched_when_tenancy_is_reinitialized()
|
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
MyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame('acme', app('tenancy_initialized_for_tenant'));
|
|
||||||
|
|
||||||
$tenant2 = Tenant::create([
|
|
||||||
'id' => 'foobar',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
$this->assertSame('foobar', app('tenancy_initialized_for_tenant'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function central_helper_runs_callbacks_in_the_central_state()
|
|
||||||
{
|
|
||||||
tenancy()->initialize($tenant = Tenant::create());
|
|
||||||
|
|
||||||
tenancy()->central(function () {
|
|
||||||
$this->assertSame(null, tenant());
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertSame($tenant, tenant());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function central_helper_returns_the_value_from_the_callback()
|
|
||||||
{
|
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$this->assertSame('foo', tenancy()->central(function () {
|
|
||||||
return 'foo';
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function central_helper_reverts_back_to_tenant_context()
|
|
||||||
{
|
|
||||||
tenancy()->initialize($tenant = Tenant::create());
|
|
||||||
|
|
||||||
tenancy()->central(function () {
|
|
||||||
//
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertSame($tenant, tenant());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function central_helper_doesnt_change_tenancy_state_when_called_in_central_context()
|
|
||||||
{
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
|
||||||
$this->assertNull(tenant());
|
|
||||||
|
|
||||||
tenancy()->central(function () {
|
|
||||||
//
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
|
||||||
$this->assertNull(tenant());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class MyBootstrapper implements TenancyBootstrapper
|
class MyBootstrapper implements TenancyBootstrapper
|
||||||
|
|
|
||||||
|
|
@ -2,226 +2,204 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Filesystem\FilesystemAdapter;
|
use Illuminate\Filesystem\FilesystemAdapter;
|
||||||
use Illuminate\Support\Facades\Cache;
|
use Illuminate\Support\Str;
|
||||||
use Illuminate\Support\Facades\DB;
|
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\Event;
|
||||||
use Illuminate\Support\Facades\Redis;
|
use Illuminate\Support\Facades\Redis;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
use Illuminate\Support\Str;
|
|
||||||
use ReflectionObject;
|
|
||||||
use ReflectionProperty;
|
|
||||||
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\TenancyEnded;
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
|
||||||
use Stancl\Tenancy\Events\TenantCreated;
|
|
||||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||||
|
use Stancl\Tenancy\Events\TenantCreated;
|
||||||
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
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
|
beforeEach(function () {
|
||||||
|
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();
|
||||||
|
|
||||||
|
$this->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 () {
|
||||||
|
config([
|
||||||
|
'tenancy.bootstrappers' => [
|
||||||
|
CacheTenancyBootstrapper::class,
|
||||||
|
],
|
||||||
|
'cache.default' => 'redis',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$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);
|
||||||
|
|
||||||
|
// Asset data didn't leak to original tenant
|
||||||
|
expect(Cache::get('foo'))->toBe('bar');
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
// Asset central is still the same
|
||||||
|
expect(Cache::get('foo'))->toBe('central');
|
||||||
|
});
|
||||||
|
|
||||||
|
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,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
$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/');
|
||||||
|
$this->assertSame('tenant' . tenant('id') . '/', getDiskPrefix('s3'), '/');
|
||||||
|
|
||||||
|
// Check suffixing logic
|
||||||
|
$new_storage_path = storage_path();
|
||||||
|
expect($new_storage_path)->toEqual($expected_storage_path);
|
||||||
|
});
|
||||||
|
|
||||||
|
function getDiskPrefix(string $disk): string
|
||||||
{
|
{
|
||||||
public $mockConsoleOutput = false;
|
/** @var FilesystemAdapter $disk */
|
||||||
|
$disk = Storage::disk($disk);
|
||||||
|
$adapter = $disk->getAdapter();
|
||||||
|
|
||||||
public function setUp(): void
|
if (! Str::startsWith(app()->version(), '9.')) {
|
||||||
{
|
return $adapter->getPathPrefix();
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
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 */
|
$prefixer = (new ReflectionObject($adapter))->getProperty('prefixer');
|
||||||
public function database_data_is_separated()
|
$prefixer->setAccessible(true);
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
DatabaseTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant1 = Tenant::create();
|
// reflection -> instance
|
||||||
$tenant2 = Tenant::create();
|
$prefixer = $prefixer->getValue($adapter);
|
||||||
|
|
||||||
$this->artisan('tenants:migrate');
|
$prefix = (new ReflectionProperty($prefixer, 'prefix'));
|
||||||
|
$prefix->setAccessible(true);
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
return $prefix->getValue($prefixer);
|
||||||
|
|
||||||
// Create Foo user
|
|
||||||
DB::table('users')->insert(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
|
||||||
$this->assertCount(1, DB::table('users')->get());
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
// Assert Foo user is not in this DB
|
|
||||||
$this->assertCount(0, DB::table('users')->get());
|
|
||||||
// Create Bar user
|
|
||||||
DB::table('users')->insert(['name' => 'Bar', 'email' => 'bar@bar.com', 'password' => 'secret']);
|
|
||||||
$this->assertCount(1, DB::table('users')->get());
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
// Assert Bar user is not in this DB
|
|
||||||
$this->assertCount(1, DB::table('users')->get());
|
|
||||||
$this->assertSame('Foo', DB::table('users')->first()->name);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function cache_data_is_separated()
|
|
||||||
{
|
|
||||||
config([
|
|
||||||
'tenancy.bootstrappers' => [
|
|
||||||
CacheTenancyBootstrapper::class,
|
|
||||||
],
|
|
||||||
'cache.default' => 'redis',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
|
|
||||||
cache()->set('foo', 'central');
|
|
||||||
$this->assertSame('central', Cache::get('foo'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
// Assert central cache doesn't leak to tenant context
|
|
||||||
$this->assertFalse(Cache::has('foo'));
|
|
||||||
|
|
||||||
cache()->set('foo', 'bar');
|
|
||||||
$this->assertSame('bar', Cache::get('foo'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
// Assert one tenant's data doesn't leak to another tenant
|
|
||||||
$this->assertFalse(Cache::has('foo'));
|
|
||||||
|
|
||||||
cache()->set('foo', 'xyz');
|
|
||||||
$this->assertSame('xyz', Cache::get('foo'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
// Asset data didn't leak to original tenant
|
|
||||||
$this->assertSame('bar', Cache::get('foo'));
|
|
||||||
|
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
// Asset central is still the same
|
|
||||||
$this->assertSame('central', Cache::get('foo'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function redis_data_is_separated()
|
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
RedisTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
Redis::set('foo', 'bar');
|
|
||||||
$this->assertSame('bar', Redis::get('foo'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
$this->assertSame(null, Redis::get('foo'));
|
|
||||||
Redis::set('foo', 'xyz');
|
|
||||||
Redis::set('abc', 'def');
|
|
||||||
$this->assertSame('xyz', Redis::get('foo'));
|
|
||||||
$this->assertSame('def', Redis::get('abc'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
$this->assertSame('bar', Redis::get('foo'));
|
|
||||||
$this->assertSame(null, Redis::get('abc'));
|
|
||||||
|
|
||||||
$tenant3 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant3);
|
|
||||||
$this->assertSame(null, Redis::get('foo'));
|
|
||||||
$this->assertSame(null, Redis::get('abc'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function filesystem_data_is_separated()
|
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
FilesystemTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$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');
|
|
||||||
$this->assertSame('bar', Storage::disk('public')->get('foo'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
$this->assertFalse(Storage::disk('public')->exists('foo'));
|
|
||||||
Storage::disk('public')->put('foo', 'xyz');
|
|
||||||
Storage::disk('public')->put('abc', 'def');
|
|
||||||
$this->assertSame('xyz', Storage::disk('public')->get('foo'));
|
|
||||||
$this->assertSame('def', Storage::disk('public')->get('abc'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
$this->assertSame('bar', Storage::disk('public')->get('foo'));
|
|
||||||
$this->assertFalse(Storage::disk('public')->exists('abc'));
|
|
||||||
|
|
||||||
$tenant3 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant3);
|
|
||||||
$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($expected_storage_path, $new_storage_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected function getDiskPrefix(string $disk): string
|
|
||||||
{
|
|
||||||
/** @var FilesystemAdapter $disk */
|
|
||||||
$disk = Storage::disk($disk);
|
|
||||||
$adapter = $disk->getAdapter();
|
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,136 +2,110 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class CacheManagerTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
config(['tenancy.bootstrappers' => [
|
||||||
public function setUp(): void
|
CacheTenancyBootstrapper::class,
|
||||||
{
|
]]);
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
config(['tenancy.bootstrappers' => [
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
CacheTenancyBootstrapper::class,
|
});
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
test('default tag is automatically applied', function () {
|
||||||
}
|
tenancy()->initialize(Tenant::create());
|
||||||
|
|
||||||
/** @test */
|
$this->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames());
|
||||||
public function default_tag_is_automatically_applied()
|
});
|
||||||
{
|
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$this->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());
|
||||||
|
|
||||||
/** @test */
|
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar'];
|
||||||
public function tags_are_merged_when_array_is_passed()
|
expect(cache()->tags(['foo', 'bar'])->getTags()->getNames())->toEqual($expected);
|
||||||
{
|
});
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar'];
|
test('tags are merged when string is passed', function () {
|
||||||
$this->assertEquals($expected, cache()->tags(['foo', 'bar'])->getTags()->getNames());
|
tenancy()->initialize(Tenant::create());
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo'];
|
||||||
public function tags_are_merged_when_string_is_passed()
|
expect(cache()->tags('foo')->getTags()->getNames())->toEqual($expected);
|
||||||
{
|
});
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo'];
|
test('exception is thrown when zero arguments are passed to tags method', function () {
|
||||||
$this->assertEquals($expected, cache()->tags('foo')->getTags()->getNames());
|
tenancy()->initialize(Tenant::create());
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$this->expectException(\Exception::class);
|
||||||
public function exception_is_thrown_when_zero_arguments_are_passed_to_tags_method()
|
cache()->tags();
|
||||||
{
|
});
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$this->expectException(\Exception::class);
|
test('exception is thrown when more than one argument is passed to tags method', function () {
|
||||||
cache()->tags();
|
tenancy()->initialize(Tenant::create());
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$this->expectException(\Exception::class);
|
||||||
public function exception_is_thrown_when_more_than_one_argument_is_passed_to_tags_method()
|
cache()->tags(1, 2);
|
||||||
{
|
});
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$this->expectException(\Exception::class);
|
test('tags separate cache well enough', function () {
|
||||||
cache()->tags(1, 2);
|
$tenant1 = Tenant::create();
|
||||||
}
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
/** @test */
|
cache()->put('foo', 'bar', 1);
|
||||||
public function tags_separate_cache_well_enough()
|
expect(cache()->get('foo'))->toBe('bar');
|
||||||
{
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
cache()->put('foo', 'bar', 1);
|
$tenant2 = Tenant::create();
|
||||||
$this->assertSame('bar', cache()->get('foo'));
|
tenancy()->initialize($tenant2);
|
||||||
|
|
||||||
$tenant2 = Tenant::create();
|
$this->assertNotSame('bar', cache()->get('foo'));
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
$this->assertNotSame('bar', cache()->get('foo'));
|
cache()->put('foo', 'xyz', 1);
|
||||||
|
expect(cache()->get('foo'))->toBe('xyz');
|
||||||
|
});
|
||||||
|
|
||||||
cache()->put('foo', 'xyz', 1);
|
test('invoking the cache helper works', function () {
|
||||||
$this->assertSame('xyz', cache()->get('foo'));
|
$tenant1 = Tenant::create();
|
||||||
}
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
/** @test */
|
cache(['foo' => 'bar'], 1);
|
||||||
public function invoking_the_cache_helper_works()
|
expect(cache('foo'))->toBe('bar');
|
||||||
{
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
cache(['foo' => 'bar'], 1);
|
$tenant2 = Tenant::create();
|
||||||
$this->assertSame('bar', cache('foo'));
|
tenancy()->initialize($tenant2);
|
||||||
|
|
||||||
$tenant2 = Tenant::create();
|
$this->assertNotSame('bar', cache('foo'));
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
$this->assertNotSame('bar', cache('foo'));
|
cache(['foo' => 'xyz'], 1);
|
||||||
|
expect(cache('foo'))->toBe('xyz');
|
||||||
|
});
|
||||||
|
|
||||||
cache(['foo' => 'xyz'], 1);
|
test('cache is persisted', function () {
|
||||||
$this->assertSame('xyz', cache('foo'));
|
$tenant1 = Tenant::create();
|
||||||
}
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
/** @test */
|
cache(['foo' => 'bar'], 10);
|
||||||
public function cache_is_persisted()
|
expect(cache('foo'))->toBe('bar');
|
||||||
{
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
cache(['foo' => 'bar'], 10);
|
tenancy()->end();
|
||||||
$this->assertSame('bar', cache('foo'));
|
|
||||||
|
|
||||||
tenancy()->end();
|
tenancy()->initialize($tenant1);
|
||||||
|
expect(cache('foo'))->toBe('bar');
|
||||||
|
});
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
test('cache is persisted when reidentification is used', function () {
|
||||||
$this->assertSame('bar', cache('foo'));
|
$tenant1 = Tenant::create();
|
||||||
}
|
$tenant2 = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
/** @test */
|
cache(['foo' => 'bar'], 10);
|
||||||
public function cache_is_persisted_when_reidentification_is_used()
|
expect(cache('foo'))->toBe('bar');
|
||||||
{
|
|
||||||
$tenant1 = Tenant::create();
|
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
cache(['foo' => 'bar'], 10);
|
tenancy()->initialize($tenant2);
|
||||||
$this->assertSame('bar', cache('foo'));
|
tenancy()->end();
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
tenancy()->initialize($tenant1);
|
||||||
tenancy()->end();
|
expect(cache('foo'))->toBe('bar');
|
||||||
|
});
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
$this->assertSame('bar', cache('foo'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,111 +2,94 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class CachedTenantResolverTest extends TestCase
|
afterEach(function () {
|
||||||
{
|
DomainTenantResolver::$shouldCache = false;
|
||||||
public function tearDown(): void
|
});
|
||||||
{
|
|
||||||
DomainTenantResolver::$shouldCache = false;
|
|
||||||
|
|
||||||
parent::tearDown();
|
test('tenants can be resolved using the cached resolver', function () {
|
||||||
}
|
$tenant = Tenant::create();
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue()->toBeTrue();
|
||||||
public function tenants_can_be_resolved_using_the_cached_resolver()
|
});
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
test('the underlying resolver is not touched when using the cached resolver', function () {
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
$tenant = Tenant::create();
|
||||||
}
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
DB::enableQueryLog();
|
||||||
public function the_underlying_resolver_is_not_touched_when_using_the_cached_resolver()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
DB::enableQueryLog();
|
DomainTenantResolver::$shouldCache = false;
|
||||||
|
|
||||||
DomainTenantResolver::$shouldCache = false;
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
DB::flushQueryLog();
|
||||||
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
||||||
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
DomainTenantResolver::$shouldCache = true;
|
||||||
DB::flushQueryLog();
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
|
||||||
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
|
||||||
|
|
||||||
DomainTenantResolver::$shouldCache = true;
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
DB::flushQueryLog();
|
||||||
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
expect(DB::getQueryLog())->toBeEmpty(); // empty
|
||||||
|
});
|
||||||
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
test('cache is invalidated when the tenant is updated', function () {
|
||||||
DB::flushQueryLog();
|
$tenant = Tenant::create();
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
$tenant->createDomain([
|
||||||
$this->assertEmpty(DB::getQueryLog()); // empty
|
'domain' => 'acme',
|
||||||
}
|
]);
|
||||||
|
|
||||||
/** @test */
|
DB::enableQueryLog();
|
||||||
public function cache_is_invalidated_when_the_tenant_is_updated()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->createDomain([
|
|
||||||
'domain' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
DB::enableQueryLog();
|
DomainTenantResolver::$shouldCache = true;
|
||||||
|
|
||||||
DomainTenantResolver::$shouldCache = true;
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
DB::flushQueryLog();
|
||||||
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
expect(DB::getQueryLog())->toBeEmpty(); // empty
|
||||||
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
$tenant->update([
|
||||||
DB::flushQueryLog();
|
'foo' => 'bar',
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
]);
|
||||||
$this->assertEmpty(DB::getQueryLog()); // empty
|
|
||||||
|
|
||||||
$tenant->update([
|
DB::flushQueryLog();
|
||||||
'foo' => 'bar',
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
]);
|
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
||||||
|
});
|
||||||
|
|
||||||
DB::flushQueryLog();
|
test('cache is invalidated when a tenants domain is changed', function () {
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
$tenant = Tenant::create();
|
||||||
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
$tenant->createDomain([
|
||||||
}
|
'domain' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
DB::enableQueryLog();
|
||||||
public function cache_is_invalidated_when_a_tenants_domain_is_changed()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->createDomain([
|
|
||||||
'domain' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
DB::enableQueryLog();
|
DomainTenantResolver::$shouldCache = true;
|
||||||
|
|
||||||
DomainTenantResolver::$shouldCache = true;
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
DB::flushQueryLog();
|
||||||
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
|
expect(DB::getQueryLog())->toBeEmpty(); // empty
|
||||||
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
$tenant->createDomain([
|
||||||
DB::flushQueryLog();
|
'domain' => 'bar',
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
]);
|
||||||
$this->assertEmpty(DB::getQueryLog()); // empty
|
|
||||||
|
|
||||||
$tenant->createDomain([
|
DB::flushQueryLog();
|
||||||
'domain' => 'bar',
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
|
||||||
]);
|
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
||||||
|
|
||||||
DB::flushQueryLog();
|
DB::flushQueryLog();
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme')));
|
expect($tenant->is(app(DomainTenantResolver::class)->resolve('bar')))->toBeTrue();
|
||||||
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
||||||
|
});
|
||||||
DB::flushQueryLog();
|
|
||||||
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('bar')));
|
|
||||||
$this->assertNotEmpty(DB::getQueryLog()); // not empty
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,76 +2,64 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
||||||
use Stancl\Tenancy\Database\Models;
|
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomainOrSubdomain;
|
||||||
|
use Stancl\Tenancy\Database\Models;
|
||||||
|
|
||||||
class CombinedDomainAndSubdomainIdentificationTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
Route::group([
|
||||||
public function setUp(): void
|
'middleware' => InitializeTenancyByDomainOrSubdomain::class,
|
||||||
{
|
], function () {
|
||||||
parent::setUp();
|
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
||||||
|
return "$a + $b";
|
||||||
Route::group([
|
|
||||||
'middleware' => InitializeTenancyByDomainOrSubdomain::class,
|
|
||||||
], function () {
|
|
||||||
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
|
||||||
return "$a + $b";
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
config(['tenancy.tenant_model' => CombinedTenant::class]);
|
config(['tenancy.tenant_model' => CombinedTenant::class]);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant can be identified by subdomain', function () {
|
||||||
public function tenant_can_be_identified_by_subdomain()
|
config(['tenancy.central_domains' => ['localhost']]);
|
||||||
{
|
|
||||||
config(['tenancy.central_domains' => ['localhost']]);
|
|
||||||
|
|
||||||
$tenant = CombinedTenant::create([
|
$tenant = CombinedTenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo',
|
'domain' => 'foo',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foo.localhost/foo/abc/xyz')
|
->get('http://foo.localhost/foo/abc/xyz')
|
||||||
->assertSee('abc + xyz');
|
->assertSee('abc + xyz');
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
$this->assertSame('acme', tenant('id'));
|
expect(tenant('id'))->toBe('acme');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant can be identified by domain', function () {
|
||||||
public function tenant_can_be_identified_by_domain()
|
config(['tenancy.central_domains' => []]);
|
||||||
{
|
|
||||||
config(['tenancy.central_domains' => []]);
|
|
||||||
|
|
||||||
$tenant = CombinedTenant::create([
|
$tenant = CombinedTenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foobar.localhost',
|
'domain' => 'foobar.localhost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foobar.localhost/foo/abc/xyz')
|
->get('http://foobar.localhost/foo/abc/xyz')
|
||||||
->assertSee('abc + xyz');
|
->assertSee('abc + xyz');
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
$this->assertSame('acme', tenant('id'));
|
expect(tenant('id'))->toBe('acme');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class CombinedTenant extends Models\Tenant
|
class CombinedTenant extends Models\Tenant
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
|
|
@ -19,219 +17,196 @@ use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Tests\Etc\ExampleSeeder;
|
use Stancl\Tenancy\Tests\Etc\ExampleSeeder;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class CommandsTest extends TestCase
|
beforeEach(function () {
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
config(['tenancy.bootstrappers' => [
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
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(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
|
||||||
|
Artisan::call('tenants:migrate');
|
||||||
|
$new_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
|
||||||
|
|
||||||
|
expect(Schema::hasTable('users'))->toBeFalse();
|
||||||
|
expect($new_connection_name)->toEqual($old_connection_name);
|
||||||
|
$this->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('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();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Incomplete test
|
||||||
|
test('seed command works');
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->artisan('tenancy:install');
|
||||||
|
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');
|
||||||
|
|
||||||
|
$this->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
|
||||||
|
->expectsOutput('Tenant: ' . $tenantId1)
|
||||||
|
->expectsOutput('Tenant: ' . $tenantId2);
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo@tests
|
||||||
|
function runCommandWorks(): void
|
||||||
{
|
{
|
||||||
public function setUp(): void
|
$id = Tenant::create()->getTenantKey();
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
config(['tenancy.bootstrappers' => [
|
test()->artisan("tenants:run foo --tenants=$id --argument='a=foo' --option='b=bar' --option='c=xyz'")
|
||||||
DatabaseTenancyBootstrapper::class,
|
->expectsOutput("User's name is Test command")
|
||||||
]]);
|
->expectsOutput('foo')
|
||||||
|
->expectsOutput('xyz');
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
}
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
|
||||||
}
|
// todo@tests
|
||||||
|
function databaseConnectionSwitchedToDefault()
|
||||||
public function tearDown(): void
|
{
|
||||||
{
|
$originalDBName = DB::connection()->getDatabaseName();
|
||||||
parent::tearDown();
|
|
||||||
|
Artisan::call('tenants:migrate');
|
||||||
// Cleanup tenancy config cache
|
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
|
||||||
if (file_exists(base_path('config/tenancy.php'))) {
|
|
||||||
unlink(base_path('config/tenancy.php'));
|
Artisan::call('tenants:seed', ['--class' => ExampleSeeder::class]);
|
||||||
}
|
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
|
||||||
}
|
|
||||||
|
Artisan::call('tenants:rollback');
|
||||||
/** @test */
|
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
|
||||||
public function migrate_command_doesnt_change_the_db_connection()
|
|
||||||
{
|
runCommandWorks();
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
|
||||||
$old_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
|
|
||||||
Artisan::call('tenants:migrate');
|
|
||||||
$new_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
$this->assertEquals($old_connection_name, $new_connection_name);
|
|
||||||
$this->assertNotEquals('tenant', $new_connection_name);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function migrate_command_works_without_options()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
Artisan::call('tenants:migrate');
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function migrate_command_works_with_tenants_option()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
Artisan::call('tenants:migrate', [
|
|
||||||
'--tenants' => [$tenant['id']],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function migrate_command_loads_schema_state()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('schema_users'));
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
Artisan::call('tenants:migrate --schema-path="tests/Etc/tenant-schema.dump"');
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('schema_users'));
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
// Check for both tables to see if missing migrations also get executed
|
|
||||||
$this->assertTrue(Schema::hasTable('schema_users'));
|
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function dump_command_works()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
Artisan::call('tenants:migrate');
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
Artisan::call('tenants:dump --path="tests/Etc/tenant-schema-test.dump"');
|
|
||||||
$this->assertFileExists('tests/Etc/tenant-schema-test.dump');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function rollback_command_works()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
Artisan::call('tenants:migrate');
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
|
||||||
Artisan::call('tenants:rollback');
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function seed_command_works()
|
|
||||||
{
|
|
||||||
$this->markTestIncomplete();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function database_connection_is_switched_to_default()
|
|
||||||
{
|
|
||||||
$originalDBName = DB::connection()->getDatabaseName();
|
|
||||||
|
|
||||||
Artisan::call('tenants:migrate');
|
|
||||||
$this->assertSame($originalDBName, DB::connection()->getDatabaseName());
|
|
||||||
|
|
||||||
Artisan::call('tenants:seed', ['--class' => ExampleSeeder::class]);
|
|
||||||
$this->assertSame($originalDBName, DB::connection()->getDatabaseName());
|
|
||||||
|
|
||||||
Artisan::call('tenants:rollback');
|
|
||||||
$this->assertSame($originalDBName, DB::connection()->getDatabaseName());
|
|
||||||
|
|
||||||
$this->run_commands_works();
|
|
||||||
$this->assertSame($originalDBName, DB::connection()->getDatabaseName());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function database_connection_is_switched_to_default_when_tenancy_has_been_initialized()
|
|
||||||
{
|
|
||||||
tenancy()->initialize(Tenant::create());
|
|
||||||
|
|
||||||
$this->database_connection_is_switched_to_default();
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function run_commands_works()
|
|
||||||
{
|
|
||||||
$id = Tenant::create()->getTenantKey();
|
|
||||||
|
|
||||||
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
|
|
||||||
|
|
||||||
$this->artisan("tenants:run foo --tenants=$id --argument='a=foo' --option='b=bar' --option='c=xyz'")
|
|
||||||
->expectsOutput("User's name is Test command")
|
|
||||||
->expectsOutput('foo')
|
|
||||||
->expectsOutput('xyz');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function install_command_works()
|
|
||||||
{
|
|
||||||
if (! is_dir($dir = app_path('Http'))) {
|
|
||||||
mkdir($dir, 0777, true);
|
|
||||||
}
|
|
||||||
if (! is_dir($dir = base_path('routes'))) {
|
|
||||||
mkdir($dir, 0777, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
$this->artisan('tenancy:install');
|
|
||||||
$this->assertFileExists(base_path('routes/tenant.php'));
|
|
||||||
$this->assertFileExists(base_path('config/tenancy.php'));
|
|
||||||
$this->assertFileExists(app_path('Providers/TenancyServiceProvider.php'));
|
|
||||||
$this->assertFileExists(database_path('migrations/2019_09_15_000010_create_tenants_table.php'));
|
|
||||||
$this->assertFileExists(database_path('migrations/2019_09_15_000020_create_domains_table.php'));
|
|
||||||
$this->assertDirectoryExists(database_path('migrations/tenant'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function migrate_fresh_command_works()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
Artisan::call('tenants:migrate-fresh');
|
|
||||||
$this->assertFalse(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
|
||||||
|
|
||||||
$this->assertFalse(DB::table('users')->exists());
|
|
||||||
DB::table('users')->insert(['name' => 'xxx', 'password' => bcrypt('password'), 'email' => 'foo@bar.xxx']);
|
|
||||||
$this->assertTrue(DB::table('users')->exists());
|
|
||||||
|
|
||||||
// test that db is wiped
|
|
||||||
Artisan::call('tenants:migrate-fresh');
|
|
||||||
$this->assertFalse(DB::table('users')->exists());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function run_command_with_array_of_tenants_works()
|
|
||||||
{
|
|
||||||
$tenantId1 = Tenant::create()->getTenantKey();
|
|
||||||
$tenantId2 = Tenant::create()->getTenantKey();
|
|
||||||
Artisan::call('tenants:migrate-fresh');
|
|
||||||
|
|
||||||
$this->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
|
|
||||||
->expectsOutput('Tenant: ' . $tenantId1)
|
|
||||||
->expectsOutput('Tenant: ' . $tenantId2);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,11 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Database\Seeder;
|
|
||||||
use Illuminate\Foundation\Auth\User as Authenticable;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Stancl\JobPipeline\JobPipeline;
|
use Stancl\JobPipeline\JobPipeline;
|
||||||
|
|
@ -16,111 +11,85 @@ use Stancl\Tenancy\Jobs\MigrateDatabase;
|
||||||
use Stancl\Tenancy\Jobs\SeedDatabase;
|
use Stancl\Tenancy\Jobs\SeedDatabase;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
use Illuminate\Foundation\Auth\User as Authenticable;
|
||||||
|
use Stancl\Tenancy\Tests\Etc\TestSeeder;
|
||||||
|
|
||||||
class DatabasePreparationTest extends TestCase
|
test('database can be created after tenant creation', function () {
|
||||||
{
|
config(['tenancy.database.template_tenant_connection' => 'mysql']);
|
||||||
/** @test */
|
|
||||||
public function database_can_be_created_after_tenant_creation()
|
|
||||||
{
|
|
||||||
config(['tenancy.database.template_tenant_connection' => 'mysql']);
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener());
|
})->toListener());
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
$manager = app(MySQLDatabaseManager::class);
|
$manager = app(MySQLDatabaseManager::class);
|
||||||
$manager->setConnection('mysql');
|
$manager->setConnection('mysql');
|
||||||
|
|
||||||
$this->assertTrue($manager->databaseExists($tenant->database()->getName()));
|
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('database can be migrated after tenant creation', function () {
|
||||||
public function database_can_be_migrated_after_tenant_creation()
|
Event::listen(TenantCreated::class, JobPipeline::make([
|
||||||
{
|
CreateDatabase::class,
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([
|
MigrateDatabase::class,
|
||||||
CreateDatabase::class,
|
])->send(function (TenantCreated $event) {
|
||||||
MigrateDatabase::class,
|
return $event->tenant;
|
||||||
])->send(function (TenantCreated $event) {
|
})->toListener());
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
$tenant->run(function () {
|
$tenant->run(function () {
|
||||||
$this->assertTrue(Schema::hasTable('users'));
|
expect(Schema::hasTable('users'))->toBeTrue();
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('database can be seeded after tenant creation', function () {
|
||||||
public function database_can_be_seeded_after_tenant_creation()
|
config(['tenancy.seeder_parameters' => [
|
||||||
{
|
'--class' => TestSeeder::class,
|
||||||
config(['tenancy.seeder_parameters' => [
|
]]);
|
||||||
'--class' => TestSeeder::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([
|
Event::listen(TenantCreated::class, JobPipeline::make([
|
||||||
CreateDatabase::class,
|
CreateDatabase::class,
|
||||||
MigrateDatabase::class,
|
MigrateDatabase::class,
|
||||||
SeedDatabase::class,
|
SeedDatabase::class,
|
||||||
])->send(function (TenantCreated $event) {
|
])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener());
|
})->toListener());
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
$tenant->run(function () {
|
$tenant->run(function () {
|
||||||
$this->assertSame('Seeded User', User::first()->name);
|
expect(User::first()->name)->toBe('Seeded User');
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('custom job can be added to the pipeline', function () {
|
||||||
public function custom_job_can_be_added_to_the_pipeline()
|
config(['tenancy.seeder_parameters' => [
|
||||||
{
|
'--class' => TestSeeder::class,
|
||||||
config(['tenancy.seeder_parameters' => [
|
]]);
|
||||||
'--class' => TestSeeder::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([
|
Event::listen(TenantCreated::class, JobPipeline::make([
|
||||||
CreateDatabase::class,
|
CreateDatabase::class,
|
||||||
MigrateDatabase::class,
|
MigrateDatabase::class,
|
||||||
SeedDatabase::class,
|
SeedDatabase::class,
|
||||||
CreateSuperuser::class,
|
CreateSuperuser::class,
|
||||||
])->send(function (TenantCreated $event) {
|
])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener());
|
})->toListener());
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
$tenant->run(function () {
|
$tenant->run(function () {
|
||||||
$this->assertSame('Foo', User::all()[1]->name);
|
expect(User::all()[1]->name)->toBe('Foo');
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class User extends Authenticable
|
class User extends Authenticable
|
||||||
{
|
{
|
||||||
protected $guarded = [];
|
protected $guarded = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestSeeder extends Seeder
|
|
||||||
{
|
|
||||||
/**
|
|
||||||
* Run the database seeds.
|
|
||||||
*
|
|
||||||
* @return void
|
|
||||||
*/
|
|
||||||
public function run()
|
|
||||||
{
|
|
||||||
DB::table('users')->insert([
|
|
||||||
'name' => 'Seeded User',
|
|
||||||
'email' => 'seeded@user',
|
|
||||||
'password' => bcrypt('password'),
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class CreateSuperuser
|
class CreateSuperuser
|
||||||
{
|
{
|
||||||
protected $tenant;
|
protected $tenant;
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
|
@ -20,111 +18,97 @@ use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class DatabaseUsersTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
config([
|
||||||
public function setUp(): void
|
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
||||||
{
|
'tenancy.database.suffix' => '',
|
||||||
parent::setUp();
|
'tenancy.database.template_tenant_connection' => 'mysql',
|
||||||
|
]);
|
||||||
|
|
||||||
config([
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
return $event->tenant;
|
||||||
'tenancy.database.suffix' => '',
|
})->toListener());
|
||||||
'tenancy.database.template_tenant_connection' => 'mysql',
|
});
|
||||||
]);
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
test('users are created when permission controlled mysql manager is used', function () {
|
||||||
return $event->tenant;
|
$tenant = new Tenant([
|
||||||
})->toListener());
|
'id' => 'foo' . Str::random(10),
|
||||||
}
|
]);
|
||||||
|
$tenant->database()->makeCredentials();
|
||||||
|
|
||||||
/** @test */
|
/** @var ManagesDatabaseUsers $manager */
|
||||||
public function users_are_created_when_permission_controlled_mysql_manager_is_used()
|
$manager = $tenant->database()->manager();
|
||||||
{
|
expect($manager->userExists($tenant->database()->getUsername()))->toBeFalse();
|
||||||
$tenant = new Tenant([
|
|
||||||
'id' => 'foo' . Str::random(10),
|
|
||||||
]);
|
|
||||||
$tenant->database()->makeCredentials();
|
|
||||||
|
|
||||||
/** @var ManagesDatabaseUsers $manager */
|
$tenant->save();
|
||||||
$manager = $tenant->database()->manager();
|
|
||||||
$this->assertFalse($manager->userExists($tenant->database()->getUsername()));
|
|
||||||
|
|
||||||
$tenant->save();
|
expect($manager->userExists($tenant->database()->getUsername()))->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
$this->assertTrue($manager->userExists($tenant->database()->getUsername()));
|
test('a tenants database cannot be created when the user already exists', function () {
|
||||||
}
|
$username = 'foo' . Str::random(8);
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_username' => $username,
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
/** @var ManagesDatabaseUsers $manager */
|
||||||
public function a_tenants_database_cannot_be_created_when_the_user_already_exists()
|
$manager = $tenant->database()->manager();
|
||||||
{
|
expect($manager->userExists($tenant->database()->getUsername()))->toBeTrue();
|
||||||
$username = 'foo' . Str::random(8);
|
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_username' => $username,
|
|
||||||
]);
|
|
||||||
|
|
||||||
/** @var ManagesDatabaseUsers $manager */
|
$this->expectException(TenantDatabaseUserAlreadyExistsException::class);
|
||||||
$manager = $tenant->database()->manager();
|
Event::fake([DatabaseCreated::class]);
|
||||||
$this->assertTrue($manager->userExists($tenant->database()->getUsername()));
|
|
||||||
$this->assertTrue($manager->databaseExists($tenant->database()->getName()));
|
|
||||||
|
|
||||||
$this->expectException(TenantDatabaseUserAlreadyExistsException::class);
|
$tenant2 = Tenant::create([
|
||||||
Event::fake([DatabaseCreated::class]);
|
'tenancy_db_username' => $username,
|
||||||
|
]);
|
||||||
|
|
||||||
$tenant2 = Tenant::create([
|
/** @var ManagesDatabaseUsers $manager */
|
||||||
'tenancy_db_username' => $username,
|
$manager2 = $tenant2->database()->manager();
|
||||||
]);
|
|
||||||
|
|
||||||
/** @var ManagesDatabaseUsers $manager */
|
// database was not created because of DB transaction
|
||||||
$manager2 = $tenant2->database()->manager();
|
expect($manager2->databaseExists($tenant2->database()->getName()))->toBeFalse();
|
||||||
|
Event::assertNotDispatched(DatabaseCreated::class);
|
||||||
|
});
|
||||||
|
|
||||||
// database was not created because of DB transaction
|
test('correct grants are given to users', function () {
|
||||||
$this->assertFalse($manager2->databaseExists($tenant2->database()->getName()));
|
PermissionControlledMySQLDatabaseManager::$grants = [
|
||||||
Event::assertNotDispatched(DatabaseCreated::class);
|
'ALTER', 'ALTER ROUTINE', 'CREATE',
|
||||||
}
|
];
|
||||||
|
|
||||||
/** @test */
|
$tenant = Tenant::create([
|
||||||
public function correct_grants_are_given_to_users()
|
'tenancy_db_username' => $user = 'user' . Str::random(8),
|
||||||
{
|
]);
|
||||||
PermissionControlledMySQLDatabaseManager::$grants = [
|
|
||||||
'ALTER', 'ALTER ROUTINE', 'CREATE',
|
|
||||||
];
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
$query = DB::connection('mysql')->select("SHOW GRANTS FOR `{$tenant->database()->getUsername()}`@`%`")[1];
|
||||||
'tenancy_db_username' => $user = 'user' . Str::random(8),
|
expect($query->{"Grants for {$user}@%"})->toStartWith('GRANT CREATE, ALTER, ALTER ROUTINE ON'); // @mysql because that's the hostname within the docker network
|
||||||
]);
|
});
|
||||||
|
|
||||||
$query = DB::connection('mysql')->select("SHOW GRANTS FOR `{$tenant->database()->getUsername()}`@`%`")[1];
|
test('having existing databases without users and switching to permission controlled mysql manager doesnt break existing dbs', function () {
|
||||||
$this->assertStringStartsWith('GRANT CREATE, ALTER, ALTER ROUTINE ON', $query->{"Grants for {$user}@%"}); // @mysql because that's the hostname within the docker network
|
config([
|
||||||
}
|
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
|
||||||
|
'tenancy.database.suffix' => '',
|
||||||
|
'tenancy.database.template_tenant_connection' => 'mysql',
|
||||||
|
'tenancy.bootstrappers' => [
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
public function having_existing_databases_without_users_and_switching_to_permission_controlled_mysql_manager_doesnt_break_existing_dbs()
|
|
||||||
{
|
|
||||||
config([
|
|
||||||
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
|
|
||||||
'tenancy.database.suffix' => '',
|
|
||||||
'tenancy.database.template_tenant_connection' => 'mysql',
|
|
||||||
'tenancy.bootstrappers' => [
|
|
||||||
DatabaseTenancyBootstrapper::class,
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
$tenant = Tenant::create([
|
||||||
|
'id' => 'foo' . Str::random(10),
|
||||||
|
]);
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
expect($tenant->database()->manager() instanceof MySQLDatabaseManager)->toBeTrue();
|
||||||
'id' => 'foo' . Str::random(10),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertTrue($tenant->database()->manager() instanceof MySQLDatabaseManager);
|
tenancy()->initialize($tenant); // check if everything works
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
tenancy()->initialize($tenant); // check if everything works
|
config(['tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class]);
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
config(['tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class]);
|
tenancy()->initialize($tenant); // check if everything works
|
||||||
|
|
||||||
tenancy()->initialize($tenant); // check if everything works
|
expect($tenant->database()->manager() instanceof PermissionControlledMySQLDatabaseManager)->toBeTrue();
|
||||||
|
expect(config('database.connections.tenant.username'))->toBe('root');
|
||||||
$this->assertTrue($tenant->database()->manager() instanceof PermissionControlledMySQLDatabaseManager);
|
});
|
||||||
$this->assertSame('root', config('database.connections.tenant.username'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,41 +2,31 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
||||||
use Stancl\Tenancy\Jobs\DeleteDomains;
|
use Stancl\Tenancy\Jobs\DeleteDomains;
|
||||||
|
|
||||||
class DeleteDomainsJobTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
config(['tenancy.tenant_model' => DatabaseAndDomainTenant::class]);
|
||||||
public function setUp(): void
|
});
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
config(['tenancy.tenant_model' => DatabaseAndDomainTenant::class]);
|
test('job delete domains successfully', function (){
|
||||||
}
|
$tenant = DatabaseAndDomainTenant::create();
|
||||||
|
|
||||||
/** @test */
|
$tenant->domains()->create([
|
||||||
public function job_delete_domains_successfully()
|
'domain' => 'foo.localhost',
|
||||||
{
|
]);
|
||||||
$tenant = DatabaseAndDomainTenant::create();
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'bar.localhost',
|
||||||
|
]);
|
||||||
|
|
||||||
$tenant->domains()->create([
|
expect($tenant->domains()->count())->toBe(2);
|
||||||
'domain' => 'foo.localhost',
|
|
||||||
]);
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'bar.localhost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertSame($tenant->domains()->count(), 2);
|
(new DeleteDomains($tenant))->handle();
|
||||||
|
|
||||||
(new DeleteDomains($tenant))->handle();
|
expect($tenant->refresh()->domains()->count())->toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
$this->assertSame($tenant->refresh()->domains()->count(), 0);
|
class DatabaseAndDomainTenant extends \Stancl\Tenancy\Tests\Etc\Tenant
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class DatabaseAndDomainTenant extends Etc\Tenant
|
|
||||||
{
|
{
|
||||||
use HasDomains;
|
use HasDomains;
|
||||||
}
|
}
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
||||||
use Stancl\Tenancy\Database\Models;
|
use Stancl\Tenancy\Database\Models;
|
||||||
|
|
@ -13,110 +11,92 @@ use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedOnDomainException;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||||
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
use Stancl\Tenancy\Resolvers\DomainTenantResolver;
|
||||||
|
|
||||||
class DomainTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
Route::group([
|
||||||
public function setUp(): void
|
'middleware' => InitializeTenancyByDomain::class,
|
||||||
{
|
], function () {
|
||||||
parent::setUp();
|
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
||||||
|
return "$a + $b";
|
||||||
Route::group([
|
|
||||||
'middleware' => InitializeTenancyByDomain::class,
|
|
||||||
], function () {
|
|
||||||
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
|
||||||
return "$a + $b";
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
config(['tenancy.tenant_model' => DomainTenant::class]);
|
config(['tenancy.tenant_model' => DomainTenant::class]);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant can be identified using hostname', function () {
|
||||||
public function tenant_can_be_identified_using_hostname()
|
$tenant = DomainTenant::create();
|
||||||
{
|
|
||||||
$tenant = DomainTenant::create();
|
|
||||||
|
|
||||||
$id = $tenant->id;
|
$id = $tenant->id;
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo.localhost',
|
'domain' => 'foo.localhost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$resolvedTenant = app(DomainTenantResolver::class)->resolve('foo.localhost');
|
$resolvedTenant = app(DomainTenantResolver::class)->resolve('foo.localhost');
|
||||||
|
|
||||||
$this->assertSame($id, $resolvedTenant->id);
|
expect($resolvedTenant->id)->toBe($id);
|
||||||
$this->assertSame(['foo.localhost'], $resolvedTenant->domains->pluck('domain')->toArray());
|
expect($resolvedTenant->domains->pluck('domain')->toArray())->toBe(['foo.localhost']);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('a domain can belong to only one tenant', function () {
|
||||||
public function a_domain_can_belong_to_only_one_tenant()
|
$tenant = DomainTenant::create();
|
||||||
{
|
|
||||||
$tenant = DomainTenant::create();
|
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo.localhost',
|
'domain' => 'foo.localhost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$tenant2 = DomainTenant::create();
|
$tenant2 = DomainTenant::create();
|
||||||
|
|
||||||
$this->expectException(DomainOccupiedByOtherTenantException::class);
|
$this->expectException(DomainOccupiedByOtherTenantException::class);
|
||||||
$tenant2->domains()->create([
|
$tenant2->domains()->create([
|
||||||
'domain' => 'foo.localhost',
|
'domain' => 'foo.localhost',
|
||||||
]);
|
]);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('an exception is thrown if tenant cannot be identified', function () {
|
||||||
public function an_exception_is_thrown_if_tenant_cannot_be_identified()
|
$this->expectException(TenantCouldNotBeIdentifiedOnDomainException::class);
|
||||||
{
|
|
||||||
$this->expectException(TenantCouldNotBeIdentifiedOnDomainException::class);
|
|
||||||
|
|
||||||
app(DomainTenantResolver::class)->resolve('foo.localhost');
|
app(DomainTenantResolver::class)->resolve('foo.localhost');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant can be identified by domain', function () {
|
||||||
public function tenant_can_be_identified_by_domain()
|
$tenant = DomainTenant::create([
|
||||||
{
|
'id' => 'acme',
|
||||||
$tenant = DomainTenant::create([
|
]);
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo.localhost',
|
'domain' => 'foo.localhost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foo.localhost/foo/abc/xyz')
|
->get('http://foo.localhost/foo/abc/xyz')
|
||||||
->assertSee('abc + xyz');
|
->assertSee('abc + xyz');
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
$this->assertSame('acme', tenant('id'));
|
expect(tenant('id'))->toBe('acme');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('onfail logic can be customized', function () {
|
||||||
public function onfail_logic_can_be_customized()
|
InitializeTenancyByDomain::$onFail = function () {
|
||||||
{
|
return 'foo';
|
||||||
InitializeTenancyByDomain::$onFail = function () {
|
};
|
||||||
return 'foo';
|
|
||||||
};
|
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foo.localhost/foo/abc/xyz')
|
->get('http://foo.localhost/foo/abc/xyz')
|
||||||
->assertSee('foo');
|
->assertSee('foo');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('domains are always lowercase', function () {
|
||||||
public function domains_are_always_lowercase()
|
$tenant = DomainTenant::create();
|
||||||
{
|
|
||||||
$tenant = DomainTenant::create();
|
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'CAPITALS',
|
'domain' => 'CAPITALS',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertSame('capitals', Domain::first()->domain);
|
expect(Domain::first()->domain)->toBe('capitals');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class DomainTenant extends Models\Tenant
|
class DomainTenant extends Models\Tenant
|
||||||
{
|
{
|
||||||
|
|
|
||||||
23
tests/Etc/TestSeeder.php
Normal file
23
tests/Etc/TestSeeder.php
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Stancl\Tenancy\Tests\Etc;
|
||||||
|
|
||||||
|
use Illuminate\Database\Seeder;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
class TestSeeder extends Seeder
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the database seeds.
|
||||||
|
*
|
||||||
|
* @return void
|
||||||
|
*/
|
||||||
|
public function run()
|
||||||
|
{
|
||||||
|
DB::table('users')->insert([
|
||||||
|
'name' => 'Seeded User',
|
||||||
|
'email' => 'seeded@user',
|
||||||
|
'password' => bcrypt('password'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Events\CallQueuedListener;
|
use Illuminate\Events\CallQueuedListener;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Queue;
|
use Illuminate\Support\Facades\Queue;
|
||||||
|
|
@ -22,183 +20,164 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\QueueableListener;
|
use Stancl\Tenancy\Listeners\QueueableListener;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class EventListenerTest extends TestCase
|
test('listeners can be synchronous', function () {
|
||||||
{
|
Queue::fake();
|
||||||
/** @test */
|
Event::listen(TenantCreated::class, FooListener::class);
|
||||||
public function listeners_can_be_synchronous()
|
|
||||||
{
|
|
||||||
Queue::fake();
|
|
||||||
Event::listen(TenantCreated::class, FooListener::class);
|
|
||||||
|
|
||||||
Tenant::create();
|
Tenant::create();
|
||||||
|
|
||||||
Queue::assertNothingPushed();
|
Queue::assertNothingPushed();
|
||||||
|
|
||||||
$this->assertSame('bar', app('foo'));
|
expect(app('foo'))->toBe('bar');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('listeners can be queued by setting a static property', function () {
|
||||||
public function listeners_can_be_queued_by_setting_a_static_property()
|
Queue::fake();
|
||||||
{
|
|
||||||
Queue::fake();
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, FooListener::class);
|
Event::listen(TenantCreated::class, FooListener::class);
|
||||||
FooListener::$shouldQueue = true;
|
FooListener::$shouldQueue = true;
|
||||||
|
|
||||||
Tenant::create();
|
Tenant::create();
|
||||||
|
|
||||||
Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) {
|
Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) {
|
||||||
return $job->class === FooListener::class;
|
return $job->class === FooListener::class;
|
||||||
});
|
});
|
||||||
|
|
||||||
$this->assertFalse(app()->bound('foo'));
|
expect(app()->bound('foo'))->toBeFalse();
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('ing events can be used to cancel tenant model actions', function () {
|
||||||
public function ing_events_can_be_used_to_cancel_tenant_model_actions()
|
Event::listen(CreatingTenant::class, function () {
|
||||||
{
|
return false;
|
||||||
Event::listen(CreatingTenant::class, function () {
|
});
|
||||||
return false;
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertSame(false, Tenant::create()->exists);
|
expect(Tenant::create()->exists)->toBe(false);
|
||||||
$this->assertSame(0, Tenant::count());
|
expect(Tenant::count())->toBe(0);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('ing events can be used to cancel domain model actions', function () {
|
||||||
public function ing_events_can_be_used_to_cancel_domain_model_actions()
|
$tenant = Tenant::create();
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
Event::listen(UpdatingDomain::class, function () {
|
Event::listen(UpdatingDomain::class, function () {
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
$domain = $tenant->domains()->create([
|
$domain = $tenant->domains()->create([
|
||||||
'domain' => 'acme',
|
'domain' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$domain->update([
|
$domain->update([
|
||||||
'domain' => 'foo',
|
'domain' => 'foo',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertSame('acme', $domain->refresh()->domain);
|
expect($domain->refresh()->domain)->toBe('acme');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('ing events can be used to cancel db creation', function () {
|
||||||
public function ing_events_can_be_used_to_cancel_db_creation()
|
Event::listen(CreatingDatabase::class, function (CreatingDatabase $event) {
|
||||||
{
|
$event->tenant->setInternal('create_database', false);
|
||||||
Event::listen(CreatingDatabase::class, function (CreatingDatabase $event) {
|
});
|
||||||
$event->tenant->setInternal('create_database', false);
|
|
||||||
});
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
dispatch_now(new CreateDatabase($tenant));
|
dispatch_now(new CreateDatabase($tenant));
|
||||||
|
|
||||||
$this->assertFalse($tenant->database()->manager()->databaseExists(
|
$this->assertFalse($tenant->database()->manager()->databaseExists(
|
||||||
$tenant->database()->getName()
|
$tenant->database()->getName()
|
||||||
));
|
));
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('ing events can be used to cancel tenancy bootstrapping', function () {
|
||||||
public function ing_events_can_be_used_to_cancel_tenancy_bootstrapping()
|
config(['tenancy.bootstrappers' => [
|
||||||
{
|
DatabaseTenancyBootstrapper::class,
|
||||||
config(['tenancy.bootstrappers' => [
|
RedisTenancyBootstrapper::class,
|
||||||
DatabaseTenancyBootstrapper::class,
|
]]);
|
||||||
RedisTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(
|
Event::listen(
|
||||||
TenantCreated::class,
|
TenantCreated::class,
|
||||||
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener()
|
})->toListener()
|
||||||
);
|
);
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
|
||||||
Event::listen(BootstrappingTenancy::class, function (BootstrappingTenancy $event) {
|
Event::listen(BootstrappingTenancy::class, function (BootstrappingTenancy $event) {
|
||||||
$event->tenancy->getBootstrappersUsing = function () {
|
$event->tenancy->getBootstrappersUsing = function () {
|
||||||
return [DatabaseTenancyBootstrapper::class];
|
return [DatabaseTenancyBootstrapper::class];
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
tenancy()->initialize(Tenant::create());
|
tenancy()->initialize(Tenant::create());
|
||||||
|
|
||||||
$this->assertSame([DatabaseTenancyBootstrapper::class], array_map('get_class', tenancy()->getBootstrappers()));
|
expect(array_map('get_class', tenancy()->getBootstrappers()))->toBe([DatabaseTenancyBootstrapper::class]);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('individual job pipelines can terminate while leaving others running', function () {
|
||||||
public function individual_job_pipelines_can_terminate_while_leaving_others_running()
|
$executed = [];
|
||||||
{
|
|
||||||
$executed = [];
|
|
||||||
|
|
||||||
Event::listen(
|
Event::listen(
|
||||||
TenantCreated::class,
|
TenantCreated::class,
|
||||||
JobPipeline::make([
|
JobPipeline::make([
|
||||||
function () use (&$executed) {
|
function () use (&$executed) {
|
||||||
$executed[] = 'P1J1';
|
$executed[] = 'P1J1';
|
||||||
},
|
},
|
||||||
|
|
||||||
function () use (&$executed) {
|
function () use (&$executed) {
|
||||||
$executed[] = 'P1J2';
|
$executed[] = 'P1J2';
|
||||||
},
|
},
|
||||||
])->send(function (TenantCreated $event) {
|
])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener()
|
})->toListener()
|
||||||
);
|
);
|
||||||
|
|
||||||
Event::listen(
|
Event::listen(
|
||||||
TenantCreated::class,
|
TenantCreated::class,
|
||||||
JobPipeline::make([
|
JobPipeline::make([
|
||||||
function () use (&$executed) {
|
function () use (&$executed) {
|
||||||
$executed[] = 'P2J1';
|
$executed[] = 'P2J1';
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
|
|
||||||
function () use (&$executed) {
|
function () use (&$executed) {
|
||||||
$executed[] = 'P2J2';
|
$executed[] = 'P2J2';
|
||||||
},
|
},
|
||||||
])->send(function (TenantCreated $event) {
|
])->send(function (TenantCreated $event) {
|
||||||
return $event->tenant;
|
return $event->tenant;
|
||||||
})->toListener()
|
})->toListener()
|
||||||
);
|
);
|
||||||
|
|
||||||
Tenant::create();
|
Tenant::create();
|
||||||
|
|
||||||
$this->assertSame([
|
$this->assertSame([
|
||||||
'P1J1',
|
'P1J1',
|
||||||
'P1J2',
|
'P1J2',
|
||||||
'P2J1', // termminated after this
|
'P2J1', // termminated after this
|
||||||
// P2J2 was not reached
|
// P2J2 was not reached
|
||||||
], $executed);
|
], $executed);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('database is not migrated if creation is disabled', function () {
|
||||||
public function database_is_not_migrated_if_creation_is_disabled()
|
Event::listen(
|
||||||
{
|
TenantCreated::class,
|
||||||
Event::listen(
|
JobPipeline::make([
|
||||||
TenantCreated::class,
|
CreateDatabase::class,
|
||||||
JobPipeline::make([
|
function () {
|
||||||
CreateDatabase::class,
|
$this->fail("The job pipeline didn't exit.");
|
||||||
function () {
|
},
|
||||||
$this->fail("The job pipeline didn't exit.");
|
MigrateDatabase::class,
|
||||||
},
|
])->send(function (TenantCreated $event) {
|
||||||
MigrateDatabase::class,
|
return $event->tenant;
|
||||||
])->send(function (TenantCreated $event) {
|
})->toListener()
|
||||||
return $event->tenant;
|
);
|
||||||
})->toListener()
|
|
||||||
);
|
|
||||||
|
|
||||||
Tenant::create([
|
Tenant::create([
|
||||||
'tenancy_create_database' => false,
|
'tenancy_create_database' => false,
|
||||||
'tenancy_db_name' => 'already_created',
|
'tenancy_db_name' => 'already_created',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertFalse($this->hasFailed());
|
expect($this->hasFailed())->toBeFalse();
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class FooListener extends QueueableListener
|
class FooListener extends QueueableListener
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,45 +2,35 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests\Features;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Features\CrossDomainRedirect;
|
use Stancl\Tenancy\Features\CrossDomainRedirect;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
use Stancl\Tenancy\Tests\TestCase;
|
|
||||||
|
|
||||||
class RedirectTest extends TestCase
|
test('tenant redirect macro replaces only the hostname', function () {
|
||||||
{
|
config([
|
||||||
/** @test */
|
'tenancy.features' => [CrossDomainRedirect::class],
|
||||||
public function tenant_redirect_macro_replaces_only_the_hostname()
|
]);
|
||||||
{
|
|
||||||
config([
|
|
||||||
'tenancy.features' => [CrossDomainRedirect::class],
|
|
||||||
]);
|
|
||||||
|
|
||||||
Route::get('/foobar', function () {
|
Route::get('/foobar', function () {
|
||||||
return 'Foo';
|
return 'Foo';
|
||||||
})->name('home');
|
})->name('home');
|
||||||
|
|
||||||
Route::get('/redirect', function () {
|
Route::get('/redirect', function () {
|
||||||
return redirect()->route('home')->domain('abcd');
|
return redirect()->route('home')->domain('abcd');
|
||||||
});
|
});
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
$this->get('/redirect')
|
$this->get('/redirect')
|
||||||
->assertRedirect('http://abcd/foobar');
|
->assertRedirect('http://abcd/foobar');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant route helper generates correct url', function () {
|
||||||
public function tenant_route_helper_generates_correct_url()
|
Route::get('/abcdef/{a?}/{b?}', function () {
|
||||||
{
|
return 'Foo';
|
||||||
Route::get('/abcdef/{a?}/{b?}', function () {
|
})->name('foo');
|
||||||
return 'Foo';
|
|
||||||
})->name('foo');
|
|
||||||
|
|
||||||
$this->assertSame('http://foo.localhost/abcdef/as/df', tenant_route('foo.localhost', 'foo', ['a' => 'as', 'b' => 'df']));
|
expect(tenant_route('foo.localhost', 'foo', ['a' => 'as', 'b' => 'df']))->toBe('http://foo.localhost/abcdef/as/df');
|
||||||
$this->assertSame('http://foo.localhost/abcdef', tenant_route('foo.localhost', 'foo', []));
|
expect(tenant_route('foo.localhost', 'foo', []))->toBe('http://foo.localhost/abcdef');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests\Features;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Stancl\Tenancy\Events\TenancyEnded;
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
|
|
@ -11,84 +9,73 @@ use Stancl\Tenancy\Features\TenantConfig;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
use Stancl\Tenancy\Tests\TestCase;
|
|
||||||
|
|
||||||
class TenantConfigTest extends TestCase
|
afterEach(function () {
|
||||||
{
|
TenantConfig::$storageToConfigMap = [];
|
||||||
public function tearDown(): void
|
});
|
||||||
{
|
|
||||||
TenantConfig::$storageToConfigMap = [];
|
|
||||||
|
|
||||||
parent::tearDown();
|
test('config is merged and removed', function () {
|
||||||
}
|
expect(config('services.paypal'))->toBe(null);
|
||||||
|
config([
|
||||||
|
'tenancy.features' => [TenantConfig::class],
|
||||||
|
'tenancy.bootstrappers' => [],
|
||||||
|
]);
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
|
||||||
/** @test */
|
TenantConfig::$storageToConfigMap = [
|
||||||
public function config_is_merged_and_removed()
|
'paypal_api_public' => 'services.paypal.public',
|
||||||
{
|
'paypal_api_private' => 'services.paypal.private',
|
||||||
$this->assertSame(null, config('services.paypal'));
|
];
|
||||||
config([
|
|
||||||
'tenancy.features' => [TenantConfig::class],
|
|
||||||
'tenancy.bootstrappers' => [],
|
|
||||||
]);
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
|
||||||
|
|
||||||
TenantConfig::$storageToConfigMap = [
|
$tenant = Tenant::create([
|
||||||
'paypal_api_public' => 'services.paypal.public',
|
'paypal_api_public' => 'foo',
|
||||||
'paypal_api_private' => 'services.paypal.private',
|
'paypal_api_private' => 'bar',
|
||||||
];
|
]);
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
tenancy()->initialize($tenant);
|
||||||
'paypal_api_public' => 'foo',
|
expect(config('services.paypal'))->toBe(['public' => 'foo', 'private' => 'bar']);
|
||||||
'paypal_api_private' => 'bar',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->end();
|
||||||
$this->assertSame(['public' => 'foo', 'private' => 'bar'], config('services.paypal'));
|
$this->assertSame([
|
||||||
|
'public' => null,
|
||||||
|
'private' => null,
|
||||||
|
], config('services.paypal'));
|
||||||
|
});
|
||||||
|
|
||||||
tenancy()->end();
|
test('the value can be set to multiple config keys', function () {
|
||||||
$this->assertSame([
|
expect(config('services.paypal'))->toBe(null);
|
||||||
'public' => null,
|
config([
|
||||||
'private' => null,
|
'tenancy.features' => [TenantConfig::class],
|
||||||
], config('services.paypal'));
|
'tenancy.bootstrappers' => [],
|
||||||
}
|
]);
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
|
||||||
/** @test */
|
TenantConfig::$storageToConfigMap = [
|
||||||
public function the_value_can_be_set_to_multiple_config_keys()
|
'paypal_api_public' => [
|
||||||
{
|
'services.paypal.public1',
|
||||||
$this->assertSame(null, config('services.paypal'));
|
'services.paypal.public2',
|
||||||
config([
|
],
|
||||||
'tenancy.features' => [TenantConfig::class],
|
'paypal_api_private' => 'services.paypal.private',
|
||||||
'tenancy.bootstrappers' => [],
|
];
|
||||||
]);
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
|
||||||
|
|
||||||
TenantConfig::$storageToConfigMap = [
|
$tenant = Tenant::create([
|
||||||
'paypal_api_public' => [
|
'paypal_api_public' => 'foo',
|
||||||
'services.paypal.public1',
|
'paypal_api_private' => 'bar',
|
||||||
'services.paypal.public2',
|
]);
|
||||||
],
|
|
||||||
'paypal_api_private' => 'services.paypal.private',
|
|
||||||
];
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
tenancy()->initialize($tenant);
|
||||||
'paypal_api_public' => 'foo',
|
$this->assertSame([
|
||||||
'paypal_api_private' => 'bar',
|
'public1' => 'foo',
|
||||||
]);
|
'public2' => 'foo',
|
||||||
|
'private' => 'bar',
|
||||||
|
], config('services.paypal'));
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->end();
|
||||||
$this->assertSame([
|
$this->assertSame([
|
||||||
'public1' => 'foo',
|
'public1' => null,
|
||||||
'public2' => 'foo',
|
'public2' => null,
|
||||||
'private' => 'bar',
|
'private' => null,
|
||||||
], config('services.paypal'));
|
], config('services.paypal'));
|
||||||
|
});
|
||||||
tenancy()->end();
|
|
||||||
$this->assertSame([
|
|
||||||
'public1' => null,
|
|
||||||
'public2' => null,
|
|
||||||
'private' => null,
|
|
||||||
], config('services.paypal'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
use Stancl\Tenancy\Bootstrappers\CacheTenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Events\TenancyEnded;
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
|
|
@ -13,49 +11,42 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class GlobalCacheTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
config(['tenancy.bootstrappers' => [
|
||||||
public function setUp(): void
|
CacheTenancyBootstrapper::class,
|
||||||
{
|
]]);
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
config(['tenancy.bootstrappers' => [
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
CacheTenancyBootstrapper::class,
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
]]);
|
});
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
test('global cache manager stores data in global cache', function () {
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
expect(cache('foo'))->toBe(null);
|
||||||
}
|
GlobalCache::put(['foo' => 'bar'], 1);
|
||||||
|
expect(GlobalCache::get('foo'))->toBe('bar');
|
||||||
|
|
||||||
/** @test */
|
$tenant1 = Tenant::create();
|
||||||
public function global_cache_manager_stores_data_in_global_cache()
|
tenancy()->initialize($tenant1);
|
||||||
{
|
expect(GlobalCache::get('foo'))->toBe('bar');
|
||||||
$this->assertSame(null, cache('foo'));
|
|
||||||
GlobalCache::put(['foo' => 'bar'], 1);
|
|
||||||
$this->assertSame('bar', GlobalCache::get('foo'));
|
|
||||||
|
|
||||||
$tenant1 = Tenant::create();
|
GlobalCache::put(['abc' => 'xyz'], 1);
|
||||||
tenancy()->initialize($tenant1);
|
cache(['def' => 'ghi'], 10);
|
||||||
$this->assertSame('bar', GlobalCache::get('foo'));
|
expect(cache('def'))->toBe('ghi');
|
||||||
|
|
||||||
GlobalCache::put(['abc' => 'xyz'], 1);
|
tenancy()->end();
|
||||||
cache(['def' => 'ghi'], 10);
|
expect(GlobalCache::get('abc'))->toBe('xyz');
|
||||||
$this->assertSame('ghi', cache('def'));
|
expect(GlobalCache::get('foo'))->toBe('bar');
|
||||||
|
expect(cache('def'))->toBe(null);
|
||||||
|
|
||||||
tenancy()->end();
|
$tenant2 = Tenant::create();
|
||||||
$this->assertSame('xyz', GlobalCache::get('abc'));
|
tenancy()->initialize($tenant2);
|
||||||
$this->assertSame('bar', GlobalCache::get('foo'));
|
expect(GlobalCache::get('abc'))->toBe('xyz');
|
||||||
$this->assertSame(null, cache('def'));
|
expect(GlobalCache::get('foo'))->toBe('bar');
|
||||||
|
expect(cache('def'))->toBe(null);
|
||||||
|
cache(['def' => 'xxx'], 1);
|
||||||
|
expect(cache('def'))->toBe('xxx');
|
||||||
|
|
||||||
$tenant2 = Tenant::create();
|
tenancy()->initialize($tenant1);
|
||||||
tenancy()->initialize($tenant2);
|
expect(cache('def'))->toBe('ghi');
|
||||||
$this->assertSame('xyz', GlobalCache::get('abc'));
|
});
|
||||||
$this->assertSame('bar', GlobalCache::get('foo'));
|
|
||||||
$this->assertSame(null, cache('def'));
|
|
||||||
cache(['def' => 'xxx'], 1);
|
|
||||||
$this->assertSame('xxx', cache('def'));
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
$this->assertSame('ghi', cache('def'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,41 +2,34 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
|
||||||
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
|
use Stancl\Tenancy\Database\Concerns\MaintenanceMode;
|
||||||
|
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||||
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
|
use Stancl\Tenancy\Middleware\CheckTenantForMaintenanceMode;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
|
||||||
|
|
||||||
class MaintenanceModeTest extends TestCase
|
test('tenant can be in maintenance mode', function () {
|
||||||
{
|
Route::get('/foo', function () {
|
||||||
/** @test */
|
return 'bar';
|
||||||
public function tenant_can_be_in_maintenance_mode()
|
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
|
||||||
{
|
|
||||||
Route::get('/foo', function () {
|
|
||||||
return 'bar';
|
|
||||||
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
|
|
||||||
|
|
||||||
$tenant = MaintenanceTenant::create();
|
$tenant = MaintenanceTenant::create();
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'acme.localhost',
|
'domain' => 'acme.localhost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->get('http://acme.localhost/foo')
|
$this->get('http://acme.localhost/foo')
|
||||||
->assertSuccessful();
|
->assertSuccessful();
|
||||||
|
|
||||||
tenancy()->end(); // flush stored tenant instance
|
tenancy()->end(); // flush stored tenant instance
|
||||||
|
|
||||||
$tenant->putDownForMaintenance();
|
$tenant->putDownForMaintenance();
|
||||||
|
|
||||||
$this->expectException(HttpException::class);
|
$this->expectException(HttpException::class);
|
||||||
$this->withoutExceptionHandling()
|
$this->withoutExceptionHandling()
|
||||||
->get('http://acme.localhost/foo');
|
->get('http://acme.localhost/foo');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class MaintenanceTenant extends Tenant
|
class MaintenanceTenant extends Tenant
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
|
use Stancl\Tenancy\Exceptions\RouteIsMissingTenantParameterException;
|
||||||
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException;
|
use Stancl\Tenancy\Exceptions\TenantCouldNotBeIdentifiedByPathException;
|
||||||
|
|
@ -11,138 +9,117 @@ use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
|
||||||
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
use Stancl\Tenancy\Resolvers\PathTenantResolver;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class PathIdentificationTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
PathTenantResolver::$tenantParameterName = 'tenant';
|
||||||
public function setUp(): void
|
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
PathTenantResolver::$tenantParameterName = 'tenant';
|
Route::group([
|
||||||
|
'prefix' => '/{tenant}',
|
||||||
Route::group([
|
'middleware' => InitializeTenancyByPath::class,
|
||||||
'prefix' => '/{tenant}',
|
], function () {
|
||||||
'middleware' => InitializeTenancyByPath::class,
|
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
||||||
], function () {
|
return "$a + $b";
|
||||||
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
|
||||||
return "$a + $b";
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
});
|
||||||
|
});
|
||||||
|
|
||||||
public function tearDown(): void
|
afterEach(function () {
|
||||||
{
|
// Global state cleanup
|
||||||
parent::tearDown();
|
PathTenantResolver::$tenantParameterName = 'tenant';
|
||||||
|
});
|
||||||
|
|
||||||
// Global state cleanup
|
test('tenant can be identified by path', function () {
|
||||||
PathTenantResolver::$tenantParameterName = 'tenant';
|
Tenant::create([
|
||||||
}
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
public function tenant_can_be_identified_by_path()
|
|
||||||
{
|
|
||||||
Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
$this->get('/acme/foo/abc/xyz');
|
||||||
|
|
||||||
$this->get('/acme/foo/abc/xyz');
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
|
expect(tenant('id'))->toBe('acme');
|
||||||
|
});
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
test('route actions dont get the tenant id', function () {
|
||||||
$this->assertSame('acme', tenant('id'));
|
Tenant::create([
|
||||||
}
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
public function route_actions_dont_get_the_tenant_id()
|
|
||||||
{
|
|
||||||
Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
$this
|
||||||
|
->get('/acme/foo/abc/xyz')
|
||||||
|
->assertContent('abc + xyz');
|
||||||
|
|
||||||
$this
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
->get('/acme/foo/abc/xyz')
|
expect(tenant('id'))->toBe('acme');
|
||||||
->assertContent('abc + xyz');
|
});
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
test('exception is thrown when tenant cannot be identified by path', function () {
|
||||||
$this->assertSame('acme', tenant('id'));
|
$this->expectException(TenantCouldNotBeIdentifiedByPathException::class);
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$this
|
||||||
public function exception_is_thrown_when_tenant_cannot_be_identified_by_path()
|
->withoutExceptionHandling()
|
||||||
{
|
->get('/acme/foo/abc/xyz');
|
||||||
$this->expectException(TenantCouldNotBeIdentifiedByPathException::class);
|
|
||||||
|
|
||||||
$this
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
->withoutExceptionHandling()
|
});
|
||||||
->get('/acme/foo/abc/xyz');
|
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
test('onfail logic can be customized', function () {
|
||||||
}
|
InitializeTenancyByPath::$onFail = function () {
|
||||||
|
return 'foo';
|
||||||
|
};
|
||||||
|
|
||||||
/** @test */
|
$this
|
||||||
public function onfail_logic_can_be_customized()
|
->get('/acme/foo/abc/xyz')
|
||||||
{
|
->assertContent('foo');
|
||||||
InitializeTenancyByPath::$onFail = function () {
|
});
|
||||||
return 'foo';
|
|
||||||
};
|
|
||||||
|
|
||||||
$this
|
test('an exception is thrown when the routes first parameter is not tenant', function () {
|
||||||
->get('/acme/foo/abc/xyz')
|
Route::group([
|
||||||
->assertContent('foo');
|
// 'prefix' => '/{tenant}', -- intentionally commented
|
||||||
}
|
'middleware' => InitializeTenancyByPath::class,
|
||||||
|
], function () {
|
||||||
/** @test */
|
Route::get('/bar/{a}/{b}', function ($a, $b) {
|
||||||
public function an_exception_is_thrown_when_the_routes_first_parameter_is_not_tenant()
|
return "$a + $b";
|
||||||
{
|
|
||||||
Route::group([
|
|
||||||
// 'prefix' => '/{tenant}', -- intentionally commented
|
|
||||||
'middleware' => InitializeTenancyByPath::class,
|
|
||||||
], function () {
|
|
||||||
Route::get('/bar/{a}/{b}', function ($a, $b) {
|
|
||||||
return "$a + $b";
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
Tenant::create([
|
Tenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->expectException(RouteIsMissingTenantParameterException::class);
|
$this->expectException(RouteIsMissingTenantParameterException::class);
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('/bar/foo/bar');
|
->get('/bar/foo/bar');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant parameter name can be customized', function () {
|
||||||
public function tenant_parameter_name_can_be_customized()
|
PathTenantResolver::$tenantParameterName = 'team';
|
||||||
{
|
|
||||||
PathTenantResolver::$tenantParameterName = 'team';
|
|
||||||
|
|
||||||
Route::group([
|
Route::group([
|
||||||
'prefix' => '/{team}',
|
'prefix' => '/{team}',
|
||||||
'middleware' => InitializeTenancyByPath::class,
|
'middleware' => InitializeTenancyByPath::class,
|
||||||
], function () {
|
], function () {
|
||||||
Route::get('/bar/{a}/{b}', function ($a, $b) {
|
Route::get('/bar/{a}/{b}', function ($a, $b) {
|
||||||
return "$a + $b";
|
return "$a + $b";
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
Tenant::create([
|
Tenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('/acme/bar/abc/xyz')
|
->get('/acme/bar/abc/xyz')
|
||||||
->assertContent('abc + xyz');
|
->assertContent('abc + xyz');
|
||||||
|
|
||||||
// Parameter for resolver is changed, so the /{tenant}/foo route will no longer work.
|
// Parameter for resolver is changed, so the /{tenant}/foo route will no longer work.
|
||||||
$this->expectException(RouteIsMissingTenantParameterException::class);
|
$this->expectException(RouteIsMissingTenantParameterException::class);
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('/acme/foo/abc/xyz');
|
->get('/acme/foo/abc/xyz');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
|
||||||
3
tests/Pest.php
Normal file
3
tests/Pest.php
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
uses(Stancl\Tenancy\Tests\TestCase::class)->in(__DIR__);
|
||||||
|
|
@ -2,264 +2,229 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Exception;
|
|
||||||
use Illuminate\Bus\Queueable;
|
use Illuminate\Bus\Queueable;
|
||||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
|
||||||
use Illuminate\Foundation\Bus\Dispatchable;
|
use Illuminate\Foundation\Bus\Dispatchable;
|
||||||
use Illuminate\Queue\Events\JobProcessed;
|
|
||||||
use Illuminate\Queue\Events\JobProcessing;
|
|
||||||
use Illuminate\Queue\InteractsWithQueue;
|
use Illuminate\Queue\InteractsWithQueue;
|
||||||
use Illuminate\Queue\SerializesModels;
|
use Illuminate\Queue\SerializesModels;
|
||||||
use Illuminate\Support\Facades\DB;
|
|
||||||
use Illuminate\Support\Facades\Event;
|
|
||||||
use Illuminate\Support\Facades\Schema;
|
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use Spatie\Valuestore\Valuestore;
|
use Spatie\Valuestore\Valuestore;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Stancl\Tenancy\Tests\Etc\User;
|
||||||
use Stancl\JobPipeline\JobPipeline;
|
use Stancl\JobPipeline\JobPipeline;
|
||||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
use Illuminate\Support\Facades\Event;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Stancl\Tenancy\Events\TenancyEnded;
|
use Stancl\Tenancy\Events\TenancyEnded;
|
||||||
use Stancl\Tenancy\Events\TenancyInitialized;
|
|
||||||
use Stancl\Tenancy\Events\TenantCreated;
|
|
||||||
use Stancl\Tenancy\Jobs\CreateDatabase;
|
use Stancl\Tenancy\Jobs\CreateDatabase;
|
||||||
|
use Stancl\Tenancy\Events\TenantCreated;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Queue\Events\JobProcessed;
|
||||||
|
use Illuminate\Queue\Events\JobProcessing;
|
||||||
|
use Stancl\Tenancy\Events\TenancyInitialized;
|
||||||
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Bootstrappers\QueueTenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Tests\Etc\User;
|
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||||
|
|
||||||
class QueueTest extends TestCase
|
beforeEach(function () {
|
||||||
|
config([
|
||||||
|
'tenancy.bootstrappers' => [
|
||||||
|
QueueTenancyBootstrapper::class,
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
],
|
||||||
|
'queue.default' => 'redis',
|
||||||
|
]);
|
||||||
|
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
||||||
|
|
||||||
|
createValueStore();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function () {
|
||||||
|
$this->valuestore->flush();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant id is passed to tenant queues', function () {
|
||||||
|
config(['queue.default' => 'sync']);
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
Event::fake([JobProcessing::class, JobProcessed::class]);
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore));
|
||||||
|
|
||||||
|
Event::assertDispatched(JobProcessing::class, function ($event) {
|
||||||
|
return $event->job->payload()['tenant_id'] === tenant('id');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant id is not passed to central queues', function () {
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
Event::fake();
|
||||||
|
|
||||||
|
config(['queue.connections.central' => [
|
||||||
|
'driver' => 'sync',
|
||||||
|
'central' => true,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore))->onConnection('central');
|
||||||
|
|
||||||
|
Event::assertDispatched(JobProcessing::class, function ($event) {
|
||||||
|
return ! isset($event->job->payload()['tenant_id']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenancy is initialized inside queues', function (bool $shouldEndTenancy) {
|
||||||
|
withTenantDatabases();
|
||||||
|
withFailedJobs();
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
withUsers();
|
||||||
|
|
||||||
|
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
|
||||||
|
|
||||||
|
$this->valuestore->put('userName', 'Bar');
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore, $user));
|
||||||
|
|
||||||
|
expect($this->valuestore->has('tenant_id'))->toBeFalse();
|
||||||
|
|
||||||
|
if ($shouldEndTenancy) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
|
||||||
|
|
||||||
|
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id);
|
||||||
|
|
||||||
|
$tenant->run(function () use ($user) {
|
||||||
|
expect($user->fresh()->name)->toBe('Bar');
|
||||||
|
});
|
||||||
|
})->with([true, false]);;
|
||||||
|
|
||||||
|
test('tenancy is initialized when retrying jobs', function (bool $shouldEndTenancy) {
|
||||||
|
if (! Str::startsWith(app()->version(), '8')) {
|
||||||
|
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
|
||||||
|
}
|
||||||
|
|
||||||
|
withFailedJobs();
|
||||||
|
withTenantDatabases();
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
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));
|
||||||
|
|
||||||
|
expect($this->valuestore->has('tenant_id'))->toBeFalse();
|
||||||
|
|
||||||
|
if ($shouldEndTenancy) {
|
||||||
|
tenancy()->end();
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(1);
|
||||||
|
expect($this->valuestore->get('tenant_id'))->toBeNull(); // job failed
|
||||||
|
|
||||||
|
$this->artisan('queue:retry all');
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
|
||||||
|
|
||||||
|
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id); // job succeeded
|
||||||
|
|
||||||
|
$tenant->run(function () use ($user) {
|
||||||
|
expect($user->fresh()->name)->toBe('Bar');
|
||||||
|
});
|
||||||
|
})->with([true, false]);
|
||||||
|
|
||||||
|
test('the tenant used by the job doesnt change when the current tenant changes', function () {
|
||||||
|
$tenant1 = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
|
dispatch(new TestJob($this->valuestore));
|
||||||
|
|
||||||
|
$tenant2 = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant2);
|
||||||
|
|
||||||
|
expect($this->valuestore->has('tenant_id'))->toBeFalse();
|
||||||
|
$this->artisan('queue:work --once');
|
||||||
|
|
||||||
|
expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: acme');
|
||||||
|
});
|
||||||
|
|
||||||
|
function createValueStore(): void
|
||||||
{
|
{
|
||||||
public $mockConsoleOutput = false;
|
$valueStorePath = __DIR__ . '/Etc/tmp/queuetest.json';
|
||||||
|
|
||||||
/** @var Valuestore */
|
if (! file_exists($valueStorePath)) {
|
||||||
protected $valuestore;
|
// The directory sometimes goes missing as well when the file is deleted in git
|
||||||
|
if (! is_dir(__DIR__ . '/Etc/tmp')) {
|
||||||
public function setUp(): void
|
mkdir(__DIR__ . '/Etc/tmp');
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
config([
|
|
||||||
'tenancy.bootstrappers' => [
|
|
||||||
QueueTenancyBootstrapper::class,
|
|
||||||
DatabaseTenancyBootstrapper::class,
|
|
||||||
],
|
|
||||||
'queue.default' => 'redis',
|
|
||||||
]);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
|
||||||
|
|
||||||
$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();
|
file_put_contents($valueStorePath, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
protected function withFailedJobs()
|
test()->valuestore = Valuestore::make($valueStorePath)->flush();
|
||||||
{
|
}
|
||||||
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()
|
function withFailedJobs()
|
||||||
{
|
{
|
||||||
Schema::create('users', function (Blueprint $table) {
|
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
|
||||||
$table->increments('id');
|
$table->increments('id');
|
||||||
$table->string('name');
|
$table->string('uuid')->unique();
|
||||||
$table->string('email')->unique();
|
$table->text('connection');
|
||||||
$table->string('password');
|
$table->text('queue');
|
||||||
$table->rememberToken();
|
$table->longText('payload');
|
||||||
$table->timestamps();
|
$table->longText('exception');
|
||||||
});
|
$table->timestamp('failed_at')->useCurrent();
|
||||||
}
|
});
|
||||||
|
}
|
||||||
|
|
||||||
protected function withTenantDatabases()
|
function withUsers()
|
||||||
{
|
{
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
Schema::create('users', function (Blueprint $table) {
|
||||||
return $event->tenant;
|
$table->increments('id');
|
||||||
})->toListener());
|
$table->string('name');
|
||||||
}
|
$table->string('email')->unique();
|
||||||
|
$table->string('password');
|
||||||
|
$table->rememberToken();
|
||||||
|
$table->timestamps();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/** @test */
|
function withTenantDatabases()
|
||||||
public function tenant_id_is_passed_to_tenant_queues()
|
{
|
||||||
{
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
config(['queue.default' => 'sync']);
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
Event::fake([JobProcessing::class, JobProcessed::class]);
|
|
||||||
|
|
||||||
dispatch(new TestJob($this->valuestore));
|
|
||||||
|
|
||||||
Event::assertDispatched(JobProcessing::class, function ($event) {
|
|
||||||
return $event->job->payload()['tenant_id'] === tenant('id');
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_id_is_not_passed_to_central_queues()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
Event::fake();
|
|
||||||
|
|
||||||
config(['queue.connections.central' => [
|
|
||||||
'driver' => 'sync',
|
|
||||||
'central' => true,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
dispatch(new TestJob($this->valuestore))->onConnection('central');
|
|
||||||
|
|
||||||
Event::assertDispatched(JobProcessing::class, function ($event) {
|
|
||||||
return ! isset($event->job->payload()['tenant_id']);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @test
|
|
||||||
*
|
|
||||||
* @testWith [true]
|
|
||||||
* [false]
|
|
||||||
*/
|
|
||||||
public function tenancy_is_initialized_inside_queues(bool $shouldEndTenancy)
|
|
||||||
{
|
|
||||||
$this->withTenantDatabases();
|
|
||||||
$this->withFailedJobs();
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$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(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 */
|
|
||||||
public function the_tenant_used_by_the_job_doesnt_change_when_the_current_tenant_changes()
|
|
||||||
{
|
|
||||||
$tenant1 = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
dispatch(new TestJob($this->valuestore));
|
|
||||||
|
|
||||||
$tenant2 = Tenant::create([
|
|
||||||
'id' => 'foobar',
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
|
||||||
|
|
||||||
$this->assertFalse($this->valuestore->has('tenant_id'));
|
|
||||||
$this->artisan('queue:work --once');
|
|
||||||
|
|
||||||
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id'));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestJob implements ShouldQueue
|
class TestJob implements ShouldQueue
|
||||||
|
|
@ -297,3 +262,4 @@ class TestJob implements ShouldQueue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,64 +2,49 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class RequestDataIdentificationTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
config([
|
||||||
public function setUp(): void
|
'tenancy.central_domains' => [
|
||||||
{
|
'localhost',
|
||||||
parent::setUp();
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
config([
|
Route::middleware(InitializeTenancyByRequestData::class)->get('/test', function () {
|
||||||
'tenancy.central_domains' => [
|
return 'Tenant id: ' . tenant('id');
|
||||||
'localhost',
|
});
|
||||||
],
|
});
|
||||||
]);
|
|
||||||
|
|
||||||
Route::middleware(InitializeTenancyByRequestData::class)->get('/test', function () {
|
afterEach(function () {
|
||||||
return 'Tenant id: ' . tenant('id');
|
InitializeTenancyByRequestData::$header = 'X-Tenant';
|
||||||
});
|
InitializeTenancyByRequestData::$queryParameter = 'tenant';
|
||||||
}
|
});
|
||||||
|
|
||||||
public function tearDown(): void
|
test('header identification works', function () {
|
||||||
{
|
InitializeTenancyByRequestData::$header = 'X-Tenant';
|
||||||
InitializeTenancyByRequestData::$header = 'X-Tenant';
|
$tenant = Tenant::create();
|
||||||
InitializeTenancyByRequestData::$queryParameter = 'tenant';
|
$tenant2 = Tenant::create();
|
||||||
|
|
||||||
parent::tearDown();
|
$this
|
||||||
}
|
->withoutExceptionHandling()
|
||||||
|
->get('test', [
|
||||||
|
'X-Tenant' => $tenant->id,
|
||||||
|
])
|
||||||
|
->assertSee($tenant->id);
|
||||||
|
});
|
||||||
|
|
||||||
/** @test */
|
test('query parameter identification works', function () {
|
||||||
public function header_identification_works()
|
InitializeTenancyByRequestData::$header = null;
|
||||||
{
|
InitializeTenancyByRequestData::$queryParameter = 'tenant';
|
||||||
InitializeTenancyByRequestData::$header = 'X-Tenant';
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
|
|
||||||
$this
|
$tenant = Tenant::create();
|
||||||
->withoutExceptionHandling()
|
$tenant2 = Tenant::create();
|
||||||
->get('test', [
|
|
||||||
'X-Tenant' => $tenant->id,
|
|
||||||
])
|
|
||||||
->assertSee($tenant->id);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$this
|
||||||
public function query_parameter_identification_works()
|
->withoutExceptionHandling()
|
||||||
{
|
->get('test?tenant=' . $tenant->id)
|
||||||
InitializeTenancyByRequestData::$header = null;
|
->assertSee($tenant->id);
|
||||||
InitializeTenancyByRequestData::$queryParameter = 'tenant';
|
});
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
|
|
||||||
$this
|
|
||||||
->withoutExceptionHandling()
|
|
||||||
->get('test?tenant=' . $tenant->id)
|
|
||||||
->assertSee($tenant->id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Session\Middleware\StartSession;
|
use Illuminate\Session\Middleware\StartSession;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
@ -13,69 +11,57 @@ use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
|
||||||
use Stancl\Tenancy\Middleware\ScopeSessions;
|
use Stancl\Tenancy\Middleware\ScopeSessions;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class ScopeSessionsTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
Route::group([
|
||||||
public function setUp(): void
|
'middleware' => [StartSession::class, InitializeTenancyBySubdomain::class, ScopeSessions::class],
|
||||||
{
|
], function () {
|
||||||
parent::setUp();
|
Route::get('/foo', function () {
|
||||||
|
return 'true';
|
||||||
Route::group([
|
|
||||||
'middleware' => [StartSession::class, InitializeTenancyBySubdomain::class, ScopeSessions::class],
|
|
||||||
], function () {
|
|
||||||
Route::get('/foo', function () {
|
|
||||||
return 'true';
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, function (TenantCreated $event) {
|
Event::listen(TenantCreated::class, function (TenantCreated $event) {
|
||||||
$tenant = $event->tenant;
|
$tenant = $event->tenant;
|
||||||
|
|
||||||
/** @var Tenant $tenant */
|
/** @var Tenant $tenant */
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => $tenant->id,
|
'domain' => $tenant->id,
|
||||||
]);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_id_is_auto_added_to_session_if_its_missing()
|
|
||||||
{
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
$this->get('http://acme.localhost/foo')
|
test('tenant id is auto added to session if its missing', function () {
|
||||||
->assertSessionHas(ScopeSessions::$tenantIdKey, 'acme');
|
$tenant = Tenant::create([
|
||||||
}
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
/** @test */
|
$this->get('http://acme.localhost/foo')
|
||||||
public function changing_tenant_id_in_session_will_abort_the_request()
|
->assertSessionHas(ScopeSessions::$tenantIdKey, 'acme');
|
||||||
{
|
});
|
||||||
$tenant = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->get('http://acme.localhost/foo')
|
test('changing tenant id in session will abort the request', function () {
|
||||||
->assertSuccessful();
|
$tenant = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
session()->put(ScopeSessions::$tenantIdKey, 'foobar');
|
$this->get('http://acme.localhost/foo')
|
||||||
|
->assertSuccessful();
|
||||||
|
|
||||||
$this->get('http://acme.localhost/foo')
|
session()->put(ScopeSessions::$tenantIdKey, 'foobar');
|
||||||
->assertStatus(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
$this->get('http://acme.localhost/foo')
|
||||||
public function an_exception_is_thrown_when_the_middleware_is_executed_before_tenancy_is_initialized()
|
->assertStatus(403);
|
||||||
{
|
});
|
||||||
Route::get('/bar', function () {
|
|
||||||
return true;
|
|
||||||
})->middleware([StartSession::class, ScopeSessions::class]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
test('an exception is thrown when the middleware is executed before tenancy is initialized', function () {
|
||||||
'id' => 'acme',
|
Route::get('/bar', function () {
|
||||||
]);
|
return true;
|
||||||
|
})->middleware([StartSession::class, ScopeSessions::class]);
|
||||||
|
|
||||||
$this->expectException(TenancyNotInitializedException::class);
|
$tenant = Tenant::create([
|
||||||
$this->withoutExceptionHandling()->get('http://acme.localhost/bar');
|
'id' => 'acme',
|
||||||
}
|
]);
|
||||||
}
|
|
||||||
|
$this->expectException(TenancyNotInitializedException::class);
|
||||||
|
$this->withoutExceptionHandling()->get('http://acme.localhost/bar');
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\QueryException;
|
use Illuminate\Database\QueryException;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
|
@ -14,309 +12,293 @@ use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
|
||||||
use Stancl\Tenancy\Database\Concerns\HasScopedValidationRules;
|
use Stancl\Tenancy\Database\Concerns\HasScopedValidationRules;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant as TestTenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant as TestTenant;
|
||||||
|
|
||||||
class SingleDatabaseTenancyTest extends TestCase
|
beforeEach(function () {
|
||||||
|
BelongsToTenant::$tenantIdColumn = 'tenant_id';
|
||||||
|
|
||||||
|
Schema::create('posts', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('text');
|
||||||
|
|
||||||
|
$table->string('tenant_id');
|
||||||
|
|
||||||
|
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
|
||||||
|
});
|
||||||
|
|
||||||
|
Schema::create('comments', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('text');
|
||||||
|
|
||||||
|
$table->unsignedInteger('post_id');
|
||||||
|
|
||||||
|
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
|
||||||
|
});
|
||||||
|
|
||||||
|
config(['tenancy.tenant_model' => Tenant::class]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('primary models are scoped to the current tenant', function () {
|
||||||
|
primaryModelsScopedToCurrentTenant();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('primary models are not scoped in the central context', function () {
|
||||||
|
primaryModelsScopedToCurrentTenant();
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
expect(Post::count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secondary models are scoped to the current tenant when accessed via primary model', function () {
|
||||||
|
secondaryModelsAreScopedToCurrentTenant();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secondary models are not scoped to the current tenant when accessed directly', function () {
|
||||||
|
secondaryModelsAreScopedToCurrentTenant();
|
||||||
|
|
||||||
|
// We're in acme context
|
||||||
|
expect(tenant('id'))->toBe('acme');
|
||||||
|
|
||||||
|
expect(Comment::count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secondary models a r e scoped to the current tenant when accessed directly and parent relationship traitis used', function () {
|
||||||
|
$acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$acme->run(function () {
|
||||||
|
$post = Post::create(['text' => 'Foo']);
|
||||||
|
$post->scoped_comments()->create(['text' => 'Comment Text']);
|
||||||
|
|
||||||
|
expect(Post::count())->toBe(1);
|
||||||
|
expect(ScopedComment::count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
$foobar = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$foobar->run(function () {
|
||||||
|
expect(Post::count())->toBe(0);
|
||||||
|
expect(ScopedComment::count())->toBe(0);
|
||||||
|
|
||||||
|
$post = Post::create(['text' => 'Bar']);
|
||||||
|
$post->scoped_comments()->create(['text' => 'Comment Text 2']);
|
||||||
|
|
||||||
|
expect(Post::count())->toBe(1);
|
||||||
|
expect(ScopedComment::count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Global context
|
||||||
|
expect(ScopedComment::count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('secondary models are not scoped in the central context', function () {
|
||||||
|
secondaryModelsAreScopedToCurrentTenant();
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
expect(Comment::count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('global models are not scoped at all', function () {
|
||||||
|
Schema::create('global_resources', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('text');
|
||||||
|
});
|
||||||
|
|
||||||
|
GlobalResource::create(['text' => 'First']);
|
||||||
|
GlobalResource::create(['text' => 'Second']);
|
||||||
|
|
||||||
|
$acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$acme->run(function () {
|
||||||
|
expect(GlobalResource::count())->toBe(2);
|
||||||
|
|
||||||
|
GlobalResource::create(['text' => 'Third']);
|
||||||
|
GlobalResource::create(['text' => 'Fourth']);
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(GlobalResource::count())->toBe(4);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant id and relationship is auto added when creating primary resources in tenant context', function () {
|
||||||
|
tenancy()->initialize($acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]));
|
||||||
|
|
||||||
|
$post = Post::create(['text' => 'Foo']);
|
||||||
|
|
||||||
|
expect($post->tenant_id)->toBe('acme');
|
||||||
|
expect($post->relationLoaded('tenant'))->toBeTrue();
|
||||||
|
expect($post->tenant)->toBe($acme);
|
||||||
|
expect($post->tenant)->toBe(tenant());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant id is not auto added when creating primary resources in central context', function () {
|
||||||
|
$this->expectException(QueryException::class);
|
||||||
|
|
||||||
|
Post::create(['text' => 'Foo']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant id column name can be customized', function () {
|
||||||
|
BelongsToTenant::$tenantIdColumn = 'team_id';
|
||||||
|
|
||||||
|
Schema::drop('comments');
|
||||||
|
Schema::drop('posts');
|
||||||
|
Schema::create('posts', function (Blueprint $table) {
|
||||||
|
$table->increments('id');
|
||||||
|
$table->string('text');
|
||||||
|
|
||||||
|
$table->string('team_id');
|
||||||
|
|
||||||
|
$table->foreign('team_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
|
||||||
|
});
|
||||||
|
|
||||||
|
tenancy()->initialize($acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]));
|
||||||
|
|
||||||
|
$post = Post::create(['text' => 'Foo']);
|
||||||
|
|
||||||
|
expect($post->team_id)->toBe('acme');
|
||||||
|
|
||||||
|
// ======================================
|
||||||
|
// foobar context
|
||||||
|
tenancy()->initialize($foobar = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]));
|
||||||
|
|
||||||
|
$post = Post::create(['text' => 'Bar']);
|
||||||
|
|
||||||
|
expect($post->team_id)->toBe('foobar');
|
||||||
|
|
||||||
|
$post = Post::first();
|
||||||
|
|
||||||
|
expect($post->team_id)->toBe('foobar');
|
||||||
|
|
||||||
|
// ======================================
|
||||||
|
// acme context again
|
||||||
|
|
||||||
|
tenancy()->initialize($acme);
|
||||||
|
|
||||||
|
$post = Post::first();
|
||||||
|
expect($post->team_id)->toBe('acme');
|
||||||
|
|
||||||
|
// Assert foobar models are inaccessible in acme context
|
||||||
|
expect(Post::count())->toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the model returned by the tenant helper has unique and exists validation rules', function () {
|
||||||
|
Schema::table('posts', function (Blueprint $table) {
|
||||||
|
$table->string('slug')->nullable();
|
||||||
|
$table->unique(['tenant_id', 'slug']);
|
||||||
|
});
|
||||||
|
|
||||||
|
tenancy()->initialize($acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]));
|
||||||
|
|
||||||
|
Post::create(['text' => 'Foo', 'slug' => 'foo']);
|
||||||
|
$data = ['text' => 'Foo 2', 'slug' => 'foo'];
|
||||||
|
|
||||||
|
$uniqueFails = Validator::make($data, [
|
||||||
|
'slug' => 'unique:posts',
|
||||||
|
])->fails();
|
||||||
|
$existsFails = Validator::make($data, [
|
||||||
|
'slug' => 'exists:posts',
|
||||||
|
])->fails();
|
||||||
|
|
||||||
|
// Assert that 'unique' and 'exists' aren't scoped by default
|
||||||
|
// $this->assertFalse($uniqueFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
|
||||||
|
// $this->assertTrue($existsFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
|
||||||
|
|
||||||
|
$uniqueFails = Validator::make($data, [
|
||||||
|
'slug' => tenant()->unique('posts'),
|
||||||
|
])->fails();
|
||||||
|
$existsFails = Validator::make($data, [
|
||||||
|
'slug' => tenant()->exists('posts'),
|
||||||
|
])->fails();
|
||||||
|
|
||||||
|
// Assert that tenant()->unique() and tenant()->exists() are scoped
|
||||||
|
expect($uniqueFails)->toBeTrue();
|
||||||
|
expect($existsFails)->toBeFalse();
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo@tests
|
||||||
|
function primaryModelsScopedToCurrentTenant()
|
||||||
{
|
{
|
||||||
public function setUp(): void
|
// acme context
|
||||||
{
|
tenancy()->initialize($acme = Tenant::create([
|
||||||
parent::setUp();
|
'id' => 'acme',
|
||||||
|
]));
|
||||||
|
|
||||||
BelongsToTenant::$tenantIdColumn = 'tenant_id';
|
$post = Post::create(['text' => 'Foo']);
|
||||||
|
|
||||||
Schema::create('posts', function (Blueprint $table) {
|
expect($post->tenant_id)->toBe('acme');
|
||||||
$table->increments('id');
|
expect($post->tenant->id)->toBe('acme');
|
||||||
$table->string('text');
|
|
||||||
|
|
||||||
$table->string('tenant_id');
|
$post = Post::first();
|
||||||
|
|
||||||
$table->foreign('tenant_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
|
expect($post->tenant_id)->toBe('acme');
|
||||||
});
|
expect($post->tenant->id)->toBe('acme');
|
||||||
|
|
||||||
Schema::create('comments', function (Blueprint $table) {
|
// ======================================
|
||||||
$table->increments('id');
|
// foobar context
|
||||||
$table->string('text');
|
tenancy()->initialize($foobar = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]));
|
||||||
|
|
||||||
$table->unsignedInteger('post_id');
|
$post = Post::create(['text' => 'Bar']);
|
||||||
|
|
||||||
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
|
expect($post->tenant_id)->toBe('foobar');
|
||||||
});
|
expect($post->tenant->id)->toBe('foobar');
|
||||||
|
|
||||||
config(['tenancy.tenant_model' => Tenant::class]);
|
$post = Post::first();
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
expect($post->tenant_id)->toBe('foobar');
|
||||||
public function primary_models_are_scoped_to_the_current_tenant()
|
expect($post->tenant->id)->toBe('foobar');
|
||||||
{
|
|
||||||
// acme context
|
|
||||||
tenancy()->initialize($acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Foo']);
|
// ======================================
|
||||||
|
// acme context again
|
||||||
|
|
||||||
$this->assertSame('acme', $post->tenant_id);
|
tenancy()->initialize($acme);
|
||||||
$this->assertSame('acme', $post->tenant->id);
|
|
||||||
|
|
||||||
$post = Post::first();
|
$post = Post::first();
|
||||||
|
expect($post->tenant_id)->toBe('acme');
|
||||||
|
expect($post->tenant->id)->toBe('acme');
|
||||||
|
|
||||||
$this->assertSame('acme', $post->tenant_id);
|
// Assert foobar models are inaccessible in acme context
|
||||||
$this->assertSame('acme', $post->tenant->id);
|
expect(Post::count())->toBe(1);
|
||||||
|
}
|
||||||
|
|
||||||
// ======================================
|
// todo@tests
|
||||||
// foobar context
|
function secondaryModelsAreScopedToCurrentTenant()
|
||||||
tenancy()->initialize($foobar = Tenant::create([
|
{
|
||||||
'id' => 'foobar',
|
// acme context
|
||||||
]));
|
tenancy()->initialize($acme = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
]));
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Bar']);
|
$post = Post::create(['text' => 'Foo']);
|
||||||
|
$post->comments()->create(['text' => 'Comment text']);
|
||||||
|
|
||||||
$this->assertSame('foobar', $post->tenant_id);
|
// ================
|
||||||
$this->assertSame('foobar', $post->tenant->id);
|
// foobar context
|
||||||
|
tenancy()->initialize($foobar = Tenant::create([
|
||||||
|
'id' => 'foobar',
|
||||||
|
]));
|
||||||
|
|
||||||
$post = Post::first();
|
$post = Post::create(['text' => 'Bar']);
|
||||||
|
$post->comments()->create(['text' => 'Comment text 2']);
|
||||||
|
|
||||||
$this->assertSame('foobar', $post->tenant_id);
|
// ================
|
||||||
$this->assertSame('foobar', $post->tenant->id);
|
// acme context again
|
||||||
|
tenancy()->initialize($acme);
|
||||||
// ======================================
|
expect(Post::count())->toBe(1);
|
||||||
// acme context again
|
expect(Post::first()->comments->count())->toBe(1);
|
||||||
|
|
||||||
tenancy()->initialize($acme);
|
|
||||||
|
|
||||||
$post = Post::first();
|
|
||||||
$this->assertSame('acme', $post->tenant_id);
|
|
||||||
$this->assertSame('acme', $post->tenant->id);
|
|
||||||
|
|
||||||
// Assert foobar models are inaccessible in acme context
|
|
||||||
$this->assertSame(1, Post::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function primary_models_are_not_scoped_in_the_central_context()
|
|
||||||
{
|
|
||||||
$this->primary_models_are_scoped_to_the_current_tenant();
|
|
||||||
|
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
$this->assertSame(2, Post::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function secondary_models_are_scoped_to_the_current_tenant_when_accessed_via_primary_model()
|
|
||||||
{
|
|
||||||
// acme context
|
|
||||||
tenancy()->initialize($acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Foo']);
|
|
||||||
$post->comments()->create(['text' => 'Comment text']);
|
|
||||||
|
|
||||||
// ================
|
|
||||||
// foobar context
|
|
||||||
tenancy()->initialize($foobar = Tenant::create([
|
|
||||||
'id' => 'foobar',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Bar']);
|
|
||||||
$post->comments()->create(['text' => 'Comment text 2']);
|
|
||||||
|
|
||||||
// ================
|
|
||||||
// acme context again
|
|
||||||
tenancy()->initialize($acme);
|
|
||||||
$this->assertSame(1, Post::count());
|
|
||||||
$this->assertSame(1, Post::first()->comments->count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function secondary_models_are_NOT_scoped_to_the_current_tenant_when_accessed_directly()
|
|
||||||
{
|
|
||||||
$this->secondary_models_are_scoped_to_the_current_tenant_when_accessed_via_primary_model();
|
|
||||||
|
|
||||||
// We're in acme context
|
|
||||||
$this->assertSame('acme', tenant('id'));
|
|
||||||
|
|
||||||
$this->assertSame(2, Comment::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function secondary_models_ARE_scoped_to_the_current_tenant_when_accessed_directly_AND_PARENT_RELATIONSHIP_TRAIT_IS_USED()
|
|
||||||
{
|
|
||||||
$acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$acme->run(function () {
|
|
||||||
$post = Post::create(['text' => 'Foo']);
|
|
||||||
$post->scoped_comments()->create(['text' => 'Comment Text']);
|
|
||||||
|
|
||||||
$this->assertSame(1, Post::count());
|
|
||||||
$this->assertSame(1, ScopedComment::count());
|
|
||||||
});
|
|
||||||
|
|
||||||
$foobar = Tenant::create([
|
|
||||||
'id' => 'foobar',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$foobar->run(function () {
|
|
||||||
$this->assertSame(0, Post::count());
|
|
||||||
$this->assertSame(0, ScopedComment::count());
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Bar']);
|
|
||||||
$post->scoped_comments()->create(['text' => 'Comment Text 2']);
|
|
||||||
|
|
||||||
$this->assertSame(1, Post::count());
|
|
||||||
$this->assertSame(1, ScopedComment::count());
|
|
||||||
});
|
|
||||||
|
|
||||||
// Global context
|
|
||||||
$this->assertSame(2, ScopedComment::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function secondary_models_are_NOT_scoped_in_the_central_context()
|
|
||||||
{
|
|
||||||
$this->secondary_models_are_scoped_to_the_current_tenant_when_accessed_via_primary_model();
|
|
||||||
|
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
$this->assertSame(2, Comment::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function global_models_are_not_scoped_at_all()
|
|
||||||
{
|
|
||||||
Schema::create('global_resources', function (Blueprint $table) {
|
|
||||||
$table->increments('id');
|
|
||||||
$table->string('text');
|
|
||||||
});
|
|
||||||
|
|
||||||
GlobalResource::create(['text' => 'First']);
|
|
||||||
GlobalResource::create(['text' => 'Second']);
|
|
||||||
|
|
||||||
$acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$acme->run(function () {
|
|
||||||
$this->assertSame(2, GlobalResource::count());
|
|
||||||
|
|
||||||
GlobalResource::create(['text' => 'Third']);
|
|
||||||
GlobalResource::create(['text' => 'Fourth']);
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertSame(4, GlobalResource::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_id_and_relationship_is_auto_added_when_creating_primary_resources_in_tenant_context()
|
|
||||||
{
|
|
||||||
tenancy()->initialize($acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Foo']);
|
|
||||||
|
|
||||||
$this->assertSame('acme', $post->tenant_id);
|
|
||||||
$this->assertTrue($post->relationLoaded('tenant'));
|
|
||||||
$this->assertSame($acme, $post->tenant);
|
|
||||||
$this->assertSame(tenant(), $post->tenant);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_id_is_not_auto_added_when_creating_primary_resources_in_central_context()
|
|
||||||
{
|
|
||||||
$this->expectException(QueryException::class);
|
|
||||||
|
|
||||||
Post::create(['text' => 'Foo']);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_id_column_name_can_be_customized()
|
|
||||||
{
|
|
||||||
BelongsToTenant::$tenantIdColumn = 'team_id';
|
|
||||||
|
|
||||||
Schema::drop('comments');
|
|
||||||
Schema::drop('posts');
|
|
||||||
Schema::create('posts', function (Blueprint $table) {
|
|
||||||
$table->increments('id');
|
|
||||||
$table->string('text');
|
|
||||||
|
|
||||||
$table->string('team_id');
|
|
||||||
|
|
||||||
$table->foreign('team_id')->references('id')->on('tenants')->onUpdate('cascade')->onDelete('cascade');
|
|
||||||
});
|
|
||||||
|
|
||||||
tenancy()->initialize($acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Foo']);
|
|
||||||
|
|
||||||
$this->assertSame('acme', $post->team_id);
|
|
||||||
|
|
||||||
// ======================================
|
|
||||||
// foobar context
|
|
||||||
tenancy()->initialize($foobar = Tenant::create([
|
|
||||||
'id' => 'foobar',
|
|
||||||
]));
|
|
||||||
|
|
||||||
$post = Post::create(['text' => 'Bar']);
|
|
||||||
|
|
||||||
$this->assertSame('foobar', $post->team_id);
|
|
||||||
|
|
||||||
$post = Post::first();
|
|
||||||
|
|
||||||
$this->assertSame('foobar', $post->team_id);
|
|
||||||
|
|
||||||
// ======================================
|
|
||||||
// acme context again
|
|
||||||
|
|
||||||
tenancy()->initialize($acme);
|
|
||||||
|
|
||||||
$post = Post::first();
|
|
||||||
$this->assertSame('acme', $post->team_id);
|
|
||||||
|
|
||||||
// Assert foobar models are inaccessible in acme context
|
|
||||||
$this->assertSame(1, Post::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function the_model_returned_by_the_tenant_helper_has_unique_and_exists_validation_rules()
|
|
||||||
{
|
|
||||||
Schema::table('posts', function (Blueprint $table) {
|
|
||||||
$table->string('slug')->nullable();
|
|
||||||
$table->unique(['tenant_id', 'slug']);
|
|
||||||
});
|
|
||||||
|
|
||||||
tenancy()->initialize($acme = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
]));
|
|
||||||
|
|
||||||
Post::create(['text' => 'Foo', 'slug' => 'foo']);
|
|
||||||
$data = ['text' => 'Foo 2', 'slug' => 'foo'];
|
|
||||||
|
|
||||||
$uniqueFails = Validator::make($data, [
|
|
||||||
'slug' => 'unique:posts',
|
|
||||||
])->fails();
|
|
||||||
$existsFails = Validator::make($data, [
|
|
||||||
'slug' => 'exists:posts',
|
|
||||||
])->fails();
|
|
||||||
|
|
||||||
// Assert that 'unique' and 'exists' aren't scoped by default
|
|
||||||
// $this->assertFalse($uniqueFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
|
|
||||||
// $this->assertTrue($existsFails); // todo get these two assertions to pass. for some reason, the validator is passing for both 'unique' and 'exists'
|
|
||||||
|
|
||||||
$uniqueFails = Validator::make($data, [
|
|
||||||
'slug' => tenant()->unique('posts'),
|
|
||||||
])->fails();
|
|
||||||
$existsFails = Validator::make($data, [
|
|
||||||
'slug' => tenant()->exists('posts'),
|
|
||||||
])->fails();
|
|
||||||
|
|
||||||
// Assert that tenant()->unique() and tenant()->exists() are scoped
|
|
||||||
$this->assertTrue($uniqueFails);
|
|
||||||
$this->assertFalse($existsFails);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class Tenant extends TestTenant
|
class Tenant extends TestTenant
|
||||||
|
|
|
||||||
|
|
@ -2,151 +2,129 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
use Stancl\Tenancy\Database\Concerns\HasDomains;
|
||||||
use Stancl\Tenancy\Database\Models;
|
|
||||||
use Stancl\Tenancy\Exceptions\NotASubdomainException;
|
use Stancl\Tenancy\Exceptions\NotASubdomainException;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;
|
||||||
|
use Stancl\Tenancy\Database\Models;
|
||||||
|
|
||||||
class SubdomainTest extends TestCase
|
beforeEach(function () {
|
||||||
{
|
// Global state cleanup after some tests
|
||||||
public function setUp(): void
|
InitializeTenancyBySubdomain::$onFail = null;
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
// Global state cleanup after some tests
|
Route::group([
|
||||||
InitializeTenancyBySubdomain::$onFail = null;
|
'middleware' => InitializeTenancyBySubdomain::class,
|
||||||
|
], function () {
|
||||||
Route::group([
|
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
||||||
'middleware' => InitializeTenancyBySubdomain::class,
|
return "$a + $b";
|
||||||
], function () {
|
|
||||||
Route::get('/foo/{a}/{b}', function ($a, $b) {
|
|
||||||
return "$a + $b";
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
config(['tenancy.tenant_model' => SubdomainTenant::class]);
|
config(['tenancy.tenant_model' => SubdomainTenant::class]);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('tenant can be identified by subdomain', function () {
|
||||||
public function tenant_can_be_identified_by_subdomain()
|
$tenant = SubdomainTenant::create([
|
||||||
{
|
'id' => 'acme',
|
||||||
$tenant = SubdomainTenant::create([
|
]);
|
||||||
'id' => 'acme',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo',
|
'domain' => 'foo',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->assertFalse(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeFalse();
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foo.localhost/foo/abc/xyz')
|
->get('http://foo.localhost/foo/abc/xyz')
|
||||||
->assertSee('abc + xyz');
|
->assertSee('abc + xyz');
|
||||||
|
|
||||||
$this->assertTrue(tenancy()->initialized);
|
expect(tenancy()->initialized)->toBeTrue();
|
||||||
$this->assertSame('acme', tenant('id'));
|
expect(tenant('id'))->toBe('acme');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('onfail logic can be customized', function () {
|
||||||
public function onfail_logic_can_be_customized()
|
InitializeTenancyBySubdomain::$onFail = function () {
|
||||||
{
|
return 'foo';
|
||||||
InitializeTenancyBySubdomain::$onFail = function () {
|
};
|
||||||
return 'foo';
|
|
||||||
};
|
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->get('http://foo.localhost/foo/abc/xyz')
|
->get('http://foo.localhost/foo/abc/xyz')
|
||||||
->assertSee('foo');
|
->assertSee('foo');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('localhost is not a valid subdomain', function () {
|
||||||
public function localhost_is_not_a_valid_subdomain()
|
$this->expectException(NotASubdomainException::class);
|
||||||
{
|
|
||||||
$this->expectException(NotASubdomainException::class);
|
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('http://localhost/foo/abc/xyz');
|
->get('http://localhost/foo/abc/xyz');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('ip address is not a valid subdomain', function () {
|
||||||
public function ip_address_is_not_a_valid_subdomain()
|
$this->expectException(NotASubdomainException::class);
|
||||||
{
|
|
||||||
$this->expectException(NotASubdomainException::class);
|
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('http://127.0.0.1/foo/abc/xyz');
|
->get('http://127.0.0.1/foo/abc/xyz');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('oninvalidsubdomain logic can be customized', function () {
|
||||||
public function oninvalidsubdomain_logic_can_be_customized()
|
// in this case, we need to return a response instance
|
||||||
{
|
// since a string would be treated as the subdomain
|
||||||
// in this case, we need to return a response instance
|
InitializeTenancyBySubdomain::$onFail = function ($e) {
|
||||||
// since a string would be treated as the subdomain
|
if ($e instanceof NotASubdomainException) {
|
||||||
InitializeTenancyBySubdomain::$onFail = function ($e) {
|
return response('foo custom invalid subdomain handler');
|
||||||
if ($e instanceof NotASubdomainException) {
|
}
|
||||||
return response('foo custom invalid subdomain handler');
|
|
||||||
}
|
|
||||||
|
|
||||||
throw $e;
|
throw $e;
|
||||||
};
|
};
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('http://127.0.0.1/foo/abc/xyz')
|
->get('http://127.0.0.1/foo/abc/xyz')
|
||||||
->assertSee('foo custom invalid subdomain handler');
|
->assertSee('foo custom invalid subdomain handler');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('we cant use a subdomain that doesnt belong to our central domains', function () {
|
||||||
public function we_cant_use_a_subdomain_that_doesnt_belong_to_our_central_domains()
|
config(['tenancy.central_domains' => [
|
||||||
{
|
'127.0.0.1',
|
||||||
config(['tenancy.central_domains' => [
|
// not 'localhost'
|
||||||
'127.0.0.1',
|
]]);
|
||||||
// not 'localhost'
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant = SubdomainTenant::create([
|
$tenant = SubdomainTenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'foo',
|
'domain' => 'foo',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->expectException(NotASubdomainException::class);
|
$this->expectException(NotASubdomainException::class);
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('http://foo.localhost/foo/abc/xyz');
|
->get('http://foo.localhost/foo/abc/xyz');
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('central domain is not a subdomain', function () {
|
||||||
public function central_domain_is_not_a_subdomain()
|
config(['tenancy.central_domains' => [
|
||||||
{
|
'localhost',
|
||||||
config(['tenancy.central_domains' => [
|
]]);
|
||||||
'localhost',
|
|
||||||
]]);
|
|
||||||
|
|
||||||
$tenant = SubdomainTenant::create([
|
$tenant = SubdomainTenant::create([
|
||||||
'id' => 'acme',
|
'id' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$tenant->domains()->create([
|
$tenant->domains()->create([
|
||||||
'domain' => 'acme',
|
'domain' => 'acme',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$this->expectException(NotASubdomainException::class);
|
$this->expectException(NotASubdomainException::class);
|
||||||
|
|
||||||
$this
|
$this
|
||||||
->withoutExceptionHandling()
|
->withoutExceptionHandling()
|
||||||
->get('http://localhost/foo/abc/xyz');
|
->get('http://localhost/foo/abc/xyz');
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
||||||
class SubdomainTenant extends Models\Tenant
|
class SubdomainTenant extends Models\Tenant
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Illuminate\Support\Facades\Storage;
|
use Illuminate\Support\Facades\Storage;
|
||||||
|
|
@ -15,115 +13,94 @@ use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class TenantAssetTest extends TestCase
|
beforeEach(function () {
|
||||||
|
config(['tenancy.bootstrappers' => [
|
||||||
|
FilesystemTenancyBootstrapper::class,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(function () {
|
||||||
|
// Cleanup
|
||||||
|
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByDomain::class;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asset can be accessed using the url returned by the tenant asset helper', function () {
|
||||||
|
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByRequestData::class;
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
$filename = 'testfile' . $this->randomString(10);
|
||||||
|
Storage::disk('public')->put($filename, 'bar');
|
||||||
|
$path = storage_path("app/public/$filename");
|
||||||
|
|
||||||
|
// response()->file() returns BinaryFileResponse whose content is
|
||||||
|
// inaccessible via getContent, so ->assertSee() can't be used
|
||||||
|
expect($path)->toBeFile();
|
||||||
|
$response = $this->get(tenant_asset($filename), [
|
||||||
|
'X-Tenant' => $tenant->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertSuccessful();
|
||||||
|
|
||||||
|
$f = fopen($path, 'r');
|
||||||
|
$content = fread($f, filesize($path));
|
||||||
|
fclose($f);
|
||||||
|
|
||||||
|
expect($content)->toBe('bar');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asset helper returns a link to tenant asset controller when asset url is null', function () {
|
||||||
|
config(['app.asset_url' => null]);
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(asset('foo'))->toBe(route('stancl.tenancy.asset', ['path' => 'foo']));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asset helper returns a link to an external url when asset url is not null', function () {
|
||||||
|
config(['app.asset_url' => 'https://an-s3-bucket']);
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(asset('foo'))->toBe("https://an-s3-bucket/tenant{$tenant->id}/foo");
|
||||||
|
});
|
||||||
|
|
||||||
|
test('global asset helper returns the same url regardless of tenancy initialization', function () {
|
||||||
|
$original = global_asset('foobar');
|
||||||
|
expect(global_asset('foobar'))->toBe(asset('foobar'));
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(global_asset('foobar'))->toBe($original);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('asset helper tenancy can be disabled', function () {
|
||||||
|
$original = asset('foo');
|
||||||
|
|
||||||
|
config([
|
||||||
|
'app.asset_url' => null,
|
||||||
|
'tenancy.filesystem.asset_helper_tenancy' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(asset('foo'))->toBe($original);
|
||||||
|
});
|
||||||
|
|
||||||
|
function getEnvironmentSetUp($app)
|
||||||
{
|
{
|
||||||
public function getEnvironmentSetUp($app)
|
$app->booted(function () {
|
||||||
{
|
if (file_exists(base_path('routes/tenant.php'))) {
|
||||||
parent::getEnvironmentSetUp($app);
|
Route::middleware(['web'])
|
||||||
|
->namespace(test()->app['config']['tenancy.tenant_route_namespace'] ?? 'App\Http\Controllers')
|
||||||
$app->booted(function () {
|
->group(base_path('routes/tenant.php'));
|
||||||
if (file_exists(base_path('routes/tenant.php'))) {
|
}
|
||||||
Route::middleware(['web'])
|
});
|
||||||
->namespace($this->app['config']['tenancy.tenant_route_namespace'] ?? 'App\Http\Controllers')
|
|
||||||
->group(base_path('routes/tenant.php'));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setUp(): void
|
|
||||||
{
|
|
||||||
parent::setUp();
|
|
||||||
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
FilesystemTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function tearDown(): void
|
|
||||||
{
|
|
||||||
parent::tearDown();
|
|
||||||
|
|
||||||
// Cleanup
|
|
||||||
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByDomain::class;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function asset_can_be_accessed_using_the_url_returned_by_the_tenant_asset_helper()
|
|
||||||
{
|
|
||||||
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByRequestData::class;
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$filename = 'testfile' . $this->randomString(10);
|
|
||||||
Storage::disk('public')->put($filename, 'bar');
|
|
||||||
$path = storage_path("app/public/$filename");
|
|
||||||
|
|
||||||
// response()->file() returns BinaryFileResponse whose content is
|
|
||||||
// inaccessible via getContent, so ->assertSee() can't be used
|
|
||||||
$this->assertFileExists($path);
|
|
||||||
$response = $this->get(tenant_asset($filename), [
|
|
||||||
'X-Tenant' => $tenant->id,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$response->assertSuccessful();
|
|
||||||
|
|
||||||
$f = fopen($path, 'r');
|
|
||||||
$content = fread($f, filesize($path));
|
|
||||||
fclose($f);
|
|
||||||
|
|
||||||
$this->assertSame('bar', $content);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function asset_helper_returns_a_link_to_TenantAssetController_when_asset_url_is_null()
|
|
||||||
{
|
|
||||||
config(['app.asset_url' => null]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame(route('stancl.tenancy.asset', ['path' => 'foo']), asset('foo'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function asset_helper_returns_a_link_to_an_external_url_when_asset_url_is_not_null()
|
|
||||||
{
|
|
||||||
config(['app.asset_url' => 'https://an-s3-bucket']);
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame("https://an-s3-bucket/tenant{$tenant->id}/foo", asset('foo'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function global_asset_helper_returns_the_same_url_regardless_of_tenancy_initialization()
|
|
||||||
{
|
|
||||||
$original = global_asset('foobar');
|
|
||||||
$this->assertSame(asset('foobar'), global_asset('foobar'));
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame($original, global_asset('foobar'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function asset_helper_tenancy_can_be_disabled()
|
|
||||||
{
|
|
||||||
$original = asset('foo');
|
|
||||||
|
|
||||||
config([
|
|
||||||
'app.asset_url' => null,
|
|
||||||
'tenancy.filesystem.asset_helper_tenancy' => false,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$this->assertSame($original, asset('foo'));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,32 +2,25 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Artisan;
|
use Illuminate\Support\Facades\Artisan;
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class TenantAwareCommandTest extends TestCase
|
test('commands run globally are tenant aware and return valid exit code', function () {
|
||||||
{
|
$tenant1 = Tenant::create();
|
||||||
/** @test */
|
$tenant2 = Tenant::create();
|
||||||
public function commands_run_globally_are_tenant_aware_and_return_valid_exit_code()
|
Artisan::call('tenants:migrate', [
|
||||||
{
|
'--tenants' => [$tenant1['id'], $tenant2['id']],
|
||||||
$tenant1 = Tenant::create();
|
]);
|
||||||
$tenant2 = Tenant::create();
|
|
||||||
Artisan::call('tenants:migrate', [
|
|
||||||
'--tenants' => [$tenant1['id'], $tenant2['id']],
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->artisan('user:add')
|
$this->artisan('user:add')
|
||||||
->assertExitCode(0);
|
->assertExitCode(0);
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
tenancy()->initialize($tenant1);
|
||||||
$this->assertNotEmpty(DB::table('users')->get());
|
$this->assertNotEmpty(DB::table('users')->get());
|
||||||
tenancy()->end();
|
tenancy()->end();
|
||||||
|
|
||||||
tenancy()->initialize($tenant2);
|
tenancy()->initialize($tenant2);
|
||||||
$this->assertNotEmpty(DB::table('users')->get());
|
$this->assertNotEmpty(DB::table('users')->get());
|
||||||
tenancy()->end();
|
tenancy()->end();
|
||||||
}
|
});
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,10 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Schema;
|
use Illuminate\Support\Facades\Schema;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
use PDO;
|
|
||||||
use Stancl\JobPipeline\JobPipeline;
|
use Stancl\JobPipeline\JobPipeline;
|
||||||
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
|
||||||
use Stancl\Tenancy\Database\DatabaseManager;
|
use Stancl\Tenancy\Database\DatabaseManager;
|
||||||
|
|
@ -27,252 +24,228 @@ use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager;
|
||||||
use Stancl\Tenancy\TenantDatabaseManagers\SQLiteDatabaseManager;
|
use Stancl\Tenancy\TenantDatabaseManagers\SQLiteDatabaseManager;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class TenantDatabaseManagerTest extends TestCase
|
test('databases can be created and deleted', function ($driver, $databaseManager) {
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
config()->set([
|
||||||
|
"tenancy.database.managers.$driver" => $databaseManager,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$name = 'db' . $this->randomString();
|
||||||
|
|
||||||
|
$manager = app($databaseManager);
|
||||||
|
$manager->setConnection($driver);
|
||||||
|
|
||||||
|
expect($manager->databaseExists($name))->toBeFalse();
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_name' => $name,
|
||||||
|
'tenancy_db_connection' => $driver,
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($manager->databaseExists($name))->toBeTrue();
|
||||||
|
$manager->deleteDatabase($tenant);
|
||||||
|
expect($manager->databaseExists($name))->toBeFalse();
|
||||||
|
})->with('database_manager_provider');
|
||||||
|
|
||||||
|
test('dbs can be created when another driver is used for the central db', function () {
|
||||||
|
expect(config('database.default'))->toBe('central');
|
||||||
|
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
$database = 'db' . $this->randomString();
|
||||||
|
|
||||||
|
$mysqlmanager = app(MySQLDatabaseManager::class);
|
||||||
|
$mysqlmanager->setConnection('mysql');
|
||||||
|
|
||||||
|
expect($mysqlmanager->databaseExists($database))->toBeFalse();
|
||||||
|
Tenant::create([
|
||||||
|
'tenancy_db_name' => $database,
|
||||||
|
'tenancy_db_connection' => 'mysql',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($mysqlmanager->databaseExists($database))->toBeTrue();
|
||||||
|
|
||||||
|
$postgresManager = app(PostgreSQLDatabaseManager::class);
|
||||||
|
$postgresManager->setConnection('pgsql');
|
||||||
|
|
||||||
|
$database = 'db' . $this->randomString();
|
||||||
|
expect($postgresManager->databaseExists($database))->toBeFalse();
|
||||||
|
|
||||||
|
Tenant::create([
|
||||||
|
'tenancy_db_name' => $database,
|
||||||
|
'tenancy_db_connection' => 'pgsql',
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect($postgresManager->databaseExists($database))->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the tenant connection is fully removed', function () {
|
||||||
|
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();
|
||||||
|
|
||||||
|
expect(array_keys(app('db')->getConnections()))->toBe(['central']);
|
||||||
|
$this->assertArrayNotHasKey('tenant', config('database.connections'));
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
createUsersTable();
|
||||||
|
|
||||||
|
expect(array_keys(app('db')->getConnections()))->toBe(['central', 'tenant']);
|
||||||
|
$this->assertArrayHasKey('tenant', config('database.connections'));
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
expect(array_keys(app('db')->getConnections()))->toBe(['central']);
|
||||||
|
expect(config('database.connections.tenant'))->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('db name is prefixed with db path when sqlite is used', function () {
|
||||||
|
if (file_exists(database_path('foodb'))) {
|
||||||
|
unlink(database_path('foodb')); // cleanup
|
||||||
|
}
|
||||||
|
config([
|
||||||
|
'database.connections.fooconn.driver' => 'sqlite',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_name' => 'foodb',
|
||||||
|
'tenancy_db_connection' => 'fooconn',
|
||||||
|
]);
|
||||||
|
app(DatabaseManager::class)->createTenantConnection($tenant);
|
||||||
|
|
||||||
|
expect(database_path('foodb'))->toBe(config('database.connections.tenant.database'));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schema manager uses schema to separate tenant dbs', function () {
|
||||||
|
config([
|
||||||
|
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
|
||||||
|
'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);
|
||||||
|
|
||||||
|
$originalDatabaseName = config(['database.connections.pgsql.database']);
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_connection' => 'pgsql',
|
||||||
|
]);
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
$schemaConfig = version_compare(app()->version(), '9.0', '>=') ?
|
||||||
|
config('database.connections.' . config('database.default') . '.search_path') :
|
||||||
|
config('database.connections.' . config('database.default') . '.schema');
|
||||||
|
|
||||||
|
expect($schemaConfig)->toBe($tenant->database()->getName());
|
||||||
|
expect(config(['database.connections.pgsql.database']))->toBe($originalDatabaseName);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a tenants database cannot be created when the database already exists', function () {
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
$name = 'foo' . Str::random(8);
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_name' => $name,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$manager = $tenant->database()->manager();
|
||||||
|
expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
|
||||||
|
|
||||||
|
$this->expectException(TenantDatabaseAlreadyExistsException::class);
|
||||||
|
$tenant2 = Tenant::create([
|
||||||
|
'tenancy_db_name' => $name,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant database can be created on a foreign server', function () {
|
||||||
|
config([
|
||||||
|
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
||||||
|
'database.connections.mysql2' => [
|
||||||
|
'driver' => 'mysql',
|
||||||
|
'host' => 'mysql2', // important line
|
||||||
|
'port' => 3306,
|
||||||
|
'database' => 'main',
|
||||||
|
'username' => 'root',
|
||||||
|
'password' => 'password',
|
||||||
|
'unix_socket' => env('DB_SOCKET', ''),
|
||||||
|
'charset' => 'utf8mb4',
|
||||||
|
'collation' => 'utf8mb4_unicode_ci',
|
||||||
|
'prefix' => '',
|
||||||
|
'prefix_indexes' => true,
|
||||||
|
'strict' => true,
|
||||||
|
'engine' => null,
|
||||||
|
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
||||||
|
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
||||||
|
]) : [],
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
$name = 'foo' . Str::random(8);
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'tenancy_db_name' => $name,
|
||||||
|
'tenancy_db_connection' => 'mysql2',
|
||||||
|
]);
|
||||||
|
|
||||||
|
/** @var PermissionControlledMySQLDatabaseManager $manager */
|
||||||
|
$manager = $tenant->database()->manager();
|
||||||
|
|
||||||
|
$manager->setConnection('mysql');
|
||||||
|
expect($manager->databaseExists($name))->toBeFalse();
|
||||||
|
|
||||||
|
$manager->setConnection('mysql2');
|
||||||
|
expect($manager->databaseExists($name))->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('path used by sqlite manager can be customized', function () {
|
||||||
|
$this->markTestIncomplete();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Datasets
|
||||||
|
dataset('database_manager_provider', [
|
||||||
|
['mysql', MySQLDatabaseManager::class],
|
||||||
|
['mysql', PermissionControlledMySQLDatabaseManager::class],
|
||||||
|
['sqlite', SQLiteDatabaseManager::class],
|
||||||
|
['pgsql', PostgreSQLDatabaseManager::class],
|
||||||
|
['pgsql', PostgreSQLSchemaManager::class],
|
||||||
|
['sqlsrv', MicrosoftSQLDatabaseManager::class]
|
||||||
|
]);
|
||||||
|
|
||||||
|
function createUsersTable()
|
||||||
{
|
{
|
||||||
/**
|
Schema::create('users', function (Blueprint $table) {
|
||||||
* @test
|
$table->increments('id');
|
||||||
* @dataProvider database_manager_provider
|
$table->string('name');
|
||||||
*/
|
$table->string('email')->unique();
|
||||||
public function databases_can_be_created_and_deleted($driver, $databaseManager)
|
$table->string('password');
|
||||||
{
|
$table->rememberToken();
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
$table->timestamps();
|
||||||
return $event->tenant;
|
});
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
config()->set([
|
|
||||||
"tenancy.database.managers.$driver" => $databaseManager,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$name = 'db' . $this->randomString();
|
|
||||||
|
|
||||||
$manager = app($databaseManager);
|
|
||||||
$manager->setConnection($driver);
|
|
||||||
|
|
||||||
$this->assertFalse($manager->databaseExists($name));
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_name' => $name,
|
|
||||||
'tenancy_db_connection' => $driver,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertTrue($manager->databaseExists($name));
|
|
||||||
$manager->deleteDatabase($tenant);
|
|
||||||
$this->assertFalse($manager->databaseExists($name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function dbs_can_be_created_when_another_driver_is_used_for_the_central_db()
|
|
||||||
{
|
|
||||||
$this->assertSame('central', config('database.default'));
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
$database = 'db' . $this->randomString();
|
|
||||||
|
|
||||||
$mysqlmanager = app(MySQLDatabaseManager::class);
|
|
||||||
$mysqlmanager->setConnection('mysql');
|
|
||||||
|
|
||||||
$this->assertFalse($mysqlmanager->databaseExists($database));
|
|
||||||
Tenant::create([
|
|
||||||
'tenancy_db_name' => $database,
|
|
||||||
'tenancy_db_connection' => 'mysql',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertTrue($mysqlmanager->databaseExists($database));
|
|
||||||
|
|
||||||
$postgresManager = app(PostgreSQLDatabaseManager::class);
|
|
||||||
$postgresManager->setConnection('pgsql');
|
|
||||||
|
|
||||||
$database = 'db' . $this->randomString();
|
|
||||||
$this->assertFalse($postgresManager->databaseExists($database));
|
|
||||||
|
|
||||||
Tenant::create([
|
|
||||||
'tenancy_db_name' => $database,
|
|
||||||
'tenancy_db_connection' => 'pgsql',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->assertTrue($postgresManager->databaseExists($database));
|
|
||||||
}
|
|
||||||
|
|
||||||
public function database_manager_provider()
|
|
||||||
{
|
|
||||||
return [
|
|
||||||
['mysql', MySQLDatabaseManager::class],
|
|
||||||
['mysql', PermissionControlledMySQLDatabaseManager::class],
|
|
||||||
['sqlite', SQLiteDatabaseManager::class],
|
|
||||||
['pgsql', PostgreSQLDatabaseManager::class],
|
|
||||||
['pgsql', PostgreSQLSchemaManager::class],
|
|
||||||
['sqlsrv', MicrosoftSQLDatabaseManager::class],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @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()
|
|
||||||
{
|
|
||||||
if (file_exists(database_path('foodb'))) {
|
|
||||||
unlink(database_path('foodb')); // cleanup
|
|
||||||
}
|
|
||||||
config([
|
|
||||||
'database.connections.fooconn.driver' => 'sqlite',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_name' => 'foodb',
|
|
||||||
'tenancy_db_connection' => 'fooconn',
|
|
||||||
]);
|
|
||||||
app(DatabaseManager::class)->createTenantConnection($tenant);
|
|
||||||
|
|
||||||
$this->assertSame(config('database.connections.tenant.database'), database_path('foodb'));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function schema_manager_uses_schema_to_separate_tenant_dbs()
|
|
||||||
{
|
|
||||||
config([
|
|
||||||
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
|
|
||||||
'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);
|
|
||||||
|
|
||||||
$originalDatabaseName = config(['database.connections.pgsql.database']);
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_connection' => 'pgsql',
|
|
||||||
]);
|
|
||||||
tenancy()->initialize($tenant);
|
|
||||||
|
|
||||||
$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']));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function a_tenants_database_cannot_be_created_when_the_database_already_exists()
|
|
||||||
{
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
$name = 'foo' . Str::random(8);
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_name' => $name,
|
|
||||||
]);
|
|
||||||
|
|
||||||
$manager = $tenant->database()->manager();
|
|
||||||
$this->assertTrue($manager->databaseExists($tenant->database()->getName()));
|
|
||||||
|
|
||||||
$this->expectException(TenantDatabaseAlreadyExistsException::class);
|
|
||||||
$tenant2 = Tenant::create([
|
|
||||||
'tenancy_db_name' => $name,
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_database_can_be_created_on_a_foreign_server()
|
|
||||||
{
|
|
||||||
config([
|
|
||||||
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
|
|
||||||
'database.connections.mysql2' => [
|
|
||||||
'driver' => 'mysql',
|
|
||||||
'host' => 'mysql2', // important line
|
|
||||||
'port' => 3306,
|
|
||||||
'database' => 'main',
|
|
||||||
'username' => 'root',
|
|
||||||
'password' => 'password',
|
|
||||||
'unix_socket' => env('DB_SOCKET', ''),
|
|
||||||
'charset' => 'utf8mb4',
|
|
||||||
'collation' => 'utf8mb4_unicode_ci',
|
|
||||||
'prefix' => '',
|
|
||||||
'prefix_indexes' => true,
|
|
||||||
'strict' => true,
|
|
||||||
'engine' => null,
|
|
||||||
'options' => extension_loaded('pdo_mysql') ? array_filter([
|
|
||||||
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
|
|
||||||
]) : [],
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
$name = 'foo' . Str::random(8);
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'tenancy_db_name' => $name,
|
|
||||||
'tenancy_db_connection' => 'mysql2',
|
|
||||||
]);
|
|
||||||
|
|
||||||
/** @var PermissionControlledMySQLDatabaseManager $manager */
|
|
||||||
$manager = $tenant->database()->manager();
|
|
||||||
|
|
||||||
$manager->setConnection('mysql');
|
|
||||||
$this->assertFalse($manager->databaseExists($name));
|
|
||||||
|
|
||||||
$manager->setConnection('mysql2');
|
|
||||||
$this->assertTrue($manager->databaseExists($name));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function path_used_by_sqlite_manager_can_be_customized()
|
|
||||||
{
|
|
||||||
$this->markTestIncomplete();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Schema\Blueprint;
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
|
|
@ -21,148 +19,127 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
use Stancl\Tenancy\UUIDGenerator;
|
use Stancl\Tenancy\UUIDGenerator;
|
||||||
|
|
||||||
class TenantModelTest extends TestCase
|
test('created event is dispatched', function () {
|
||||||
{
|
Event::fake([TenantCreated::class]);
|
||||||
/** @test */
|
|
||||||
public function created_event_is_dispatched()
|
|
||||||
{
|
|
||||||
Event::fake([TenantCreated::class]);
|
|
||||||
|
|
||||||
Event::assertNotDispatched(TenantCreated::class);
|
Event::assertNotDispatched(TenantCreated::class);
|
||||||
|
|
||||||
Tenant::create();
|
Tenant::create();
|
||||||
|
|
||||||
Event::assertDispatched(TenantCreated::class);
|
Event::assertDispatched(TenantCreated::class);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('current tenant can be resolved from service container using typehint', function () {
|
||||||
public function current_tenant_can_be_resolved_from_service_container_using_typehint()
|
$tenant = Tenant::create();
|
||||||
{
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
$this->assertSame($tenant->id, app(Contracts\Tenant::class)->id);
|
expect(app(Contracts\Tenant::class)->id)->toBe($tenant->id);
|
||||||
|
|
||||||
tenancy()->end();
|
tenancy()->end();
|
||||||
|
|
||||||
$this->assertSame(null, app(Contracts\Tenant::class));
|
expect(app(Contracts\Tenant::class))->toBe(null);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('id is generated when no id is supplied', function () {
|
||||||
public function id_is_generated_when_no_id_is_supplied()
|
config(['tenancy.id_generator' => UUIDGenerator::class]);
|
||||||
{
|
|
||||||
config(['tenancy.id_generator' => UUIDGenerator::class]);
|
|
||||||
|
|
||||||
$this->mock(UUIDGenerator::class, function ($mock) {
|
$this->mock(UUIDGenerator::class, function ($mock) {
|
||||||
return $mock->shouldReceive('generate')->once();
|
return $mock->shouldReceive('generate')->once();
|
||||||
});
|
});
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
$tenant = Tenant::create();
|
||||||
|
|
||||||
$this->assertNotNull($tenant->id);
|
$this->assertNotNull($tenant->id);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('autoincrement ids are supported', function () {
|
||||||
public function autoincrement_ids_are_supported()
|
Schema::drop('domains');
|
||||||
{
|
Schema::table('tenants', function (Blueprint $table) {
|
||||||
Schema::drop('domains');
|
$table->bigIncrements('id')->change();
|
||||||
Schema::table('tenants', function (Blueprint $table) {
|
});
|
||||||
$table->bigIncrements('id')->change();
|
|
||||||
});
|
|
||||||
|
|
||||||
unset(app()[UniqueIdentifierGenerator::class]);
|
unset(app()[UniqueIdentifierGenerator::class]);
|
||||||
|
|
||||||
$tenant1 = Tenant::create();
|
$tenant1 = Tenant::create();
|
||||||
$tenant2 = Tenant::create();
|
$tenant2 = Tenant::create();
|
||||||
|
|
||||||
$this->assertSame(1, $tenant1->id);
|
expect($tenant1->id)->toBe(1);
|
||||||
$this->assertSame(2, $tenant2->id);
|
expect($tenant2->id)->toBe(2);
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('custom tenant model can be used', function () {
|
||||||
public function custom_tenant_model_can_be_used()
|
$tenant = MyTenant::create();
|
||||||
{
|
|
||||||
$tenant = MyTenant::create();
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
$this->assertTrue(tenant() instanceof MyTenant);
|
expect(tenant() instanceof MyTenant)->toBeTrue();
|
||||||
}
|
});
|
||||||
|
|
||||||
/** @test */
|
test('custom tenant model that doesnt extend vendor tenant model can be used', function () {
|
||||||
public function custom_tenant_model_that_doesnt_extend_vendor_Tenant_model_can_be_used()
|
$tenant = AnotherTenant::create([
|
||||||
{
|
'id' => 'acme',
|
||||||
$tenant = AnotherTenant::create([
|
]);
|
||||||
'id' => 'acme',
|
|
||||||
|
tenancy()->initialize($tenant);
|
||||||
|
|
||||||
|
expect(tenant() instanceof AnotherTenant)->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant can be created even when we are in another tenants context', function () {
|
||||||
|
config(['tenancy.bootstrappers' => [
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
]]);
|
||||||
|
|
||||||
|
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
||||||
|
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function ($event) {
|
||||||
|
return $event->tenant;
|
||||||
|
})->toListener());
|
||||||
|
|
||||||
|
$tenant1 = Tenant::create([
|
||||||
|
'id' => 'foo',
|
||||||
|
'tenancy_db_name' => 'db' . Str::random(16),
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->initialize($tenant1);
|
||||||
|
|
||||||
|
$tenant2 = Tenant::create([
|
||||||
|
'id' => 'bar',
|
||||||
|
'tenancy_db_name' => 'db' . Str::random(16),
|
||||||
|
]);
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
expect(Tenant::count())->toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('the model uses tenant collection', function () {
|
||||||
|
Tenant::create();
|
||||||
|
Tenant::create();
|
||||||
|
|
||||||
|
expect(Tenant::count())->toBe(2);
|
||||||
|
expect(Tenant::all() instanceof TenantCollection)->toBeTrue();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a command can be run on a collection of tenants', function () {
|
||||||
|
Tenant::create([
|
||||||
|
'id' => 't1',
|
||||||
|
'foo' => 'bar',
|
||||||
|
]);
|
||||||
|
Tenant::create([
|
||||||
|
'id' => 't2',
|
||||||
|
'foo' => 'bar',
|
||||||
|
]);
|
||||||
|
|
||||||
|
Tenant::all()->runForEach(function ($tenant) {
|
||||||
|
$tenant->update([
|
||||||
|
'foo' => 'xyz',
|
||||||
]);
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
tenancy()->initialize($tenant);
|
expect(Tenant::find('t1')->foo)->toBe('xyz');
|
||||||
|
expect(Tenant::find('t2')->foo)->toBe('xyz');
|
||||||
$this->assertTrue(tenant() instanceof AnotherTenant);
|
});
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_can_be_created_even_when_we_are_in_another_tenants_context()
|
|
||||||
{
|
|
||||||
config(['tenancy.bootstrappers' => [
|
|
||||||
DatabaseTenancyBootstrapper::class,
|
|
||||||
]]);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function ($event) {
|
|
||||||
return $event->tenant;
|
|
||||||
})->toListener());
|
|
||||||
|
|
||||||
$tenant1 = Tenant::create([
|
|
||||||
'id' => 'foo',
|
|
||||||
'tenancy_db_name' => 'db' . Str::random(16),
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->initialize($tenant1);
|
|
||||||
|
|
||||||
$tenant2 = Tenant::create([
|
|
||||||
'id' => 'bar',
|
|
||||||
'tenancy_db_name' => 'db' . Str::random(16),
|
|
||||||
]);
|
|
||||||
|
|
||||||
tenancy()->end();
|
|
||||||
|
|
||||||
$this->assertSame(2, Tenant::count());
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function the_model_uses_TenantCollection()
|
|
||||||
{
|
|
||||||
Tenant::create();
|
|
||||||
Tenant::create();
|
|
||||||
|
|
||||||
$this->assertSame(2, Tenant::count());
|
|
||||||
$this->assertTrue(Tenant::all() instanceof TenantCollection);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function a_command_can_be_run_on_a_collection_of_tenants()
|
|
||||||
{
|
|
||||||
Tenant::create([
|
|
||||||
'id' => 't1',
|
|
||||||
'foo' => 'bar',
|
|
||||||
]);
|
|
||||||
Tenant::create([
|
|
||||||
'id' => 't2',
|
|
||||||
'foo' => 'bar',
|
|
||||||
]);
|
|
||||||
|
|
||||||
Tenant::all()->runForEach(function ($tenant) {
|
|
||||||
$tenant->update([
|
|
||||||
'foo' => 'xyz',
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
$this->assertSame('xyz', Tenant::find('t1')->foo);
|
|
||||||
$this->assertSame('xyz', Tenant::find('t2')->foo);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class MyTenant extends Tenant
|
class MyTenant extends Tenant
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,9 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Carbon\Carbon;
|
use Carbon\Carbon;
|
||||||
use Carbon\CarbonInterval;
|
use Carbon\CarbonInterval;
|
||||||
use Closure;
|
|
||||||
use Illuminate\Auth\SessionGuard;
|
use Illuminate\Auth\SessionGuard;
|
||||||
use Illuminate\Foundation\Auth\User as Authenticable;
|
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\Event;
|
use Illuminate\Support\Facades\Event;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
@ -26,249 +22,234 @@ use Stancl\Tenancy\Listeners\RevertToCentralContext;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
use Illuminate\Foundation\Auth\User as Authenticable;
|
||||||
|
|
||||||
class TenantUserImpersonationTest extends TestCase
|
beforeEach(function () {
|
||||||
|
$this->artisan('migrate', [
|
||||||
|
'--path' => __DIR__ . '/../assets/impersonation-migrations',
|
||||||
|
'--realpath' => true,
|
||||||
|
])->assertExitCode(0);
|
||||||
|
|
||||||
|
config([
|
||||||
|
'tenancy.bootstrappers' => [
|
||||||
|
DatabaseTenancyBootstrapper::class,
|
||||||
|
],
|
||||||
|
'tenancy.features' => [
|
||||||
|
UserImpersonation::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);
|
||||||
|
|
||||||
|
config(['auth.providers.users.model' => ImpersonationUser::class]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant user can be impersonated on a tenant domain', function () {
|
||||||
|
Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'foo.localhost',
|
||||||
|
]);
|
||||||
|
migrateTenants();
|
||||||
|
$user = $tenant->run(function () {
|
||||||
|
return ImpersonationUser::create([
|
||||||
|
'name' => 'Joe',
|
||||||
|
'email' => 'joe@local',
|
||||||
|
'password' => bcrypt('secret'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// We try to visit the dashboard directly, before impersonating the user.
|
||||||
|
$this->get('http://foo.localhost/dashboard')
|
||||||
|
->assertRedirect('http://foo.localhost/login');
|
||||||
|
|
||||||
|
// We impersonate the user
|
||||||
|
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
||||||
|
$this->get('http://foo.localhost/impersonate/' . $token->token)
|
||||||
|
->assertRedirect('http://foo.localhost/dashboard');
|
||||||
|
|
||||||
|
// Now we try to visit the dashboard directly, after impersonating the user.
|
||||||
|
$this->get('http://foo.localhost/dashboard')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('You are logged in as Joe');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tenant user can be impersonated on a tenant path', function () {
|
||||||
|
makeLoginRoute();
|
||||||
|
|
||||||
|
Route::middleware(InitializeTenancyByPath::class)->prefix('/{tenant}')->group(getRoutes(false));
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'id' => 'acme',
|
||||||
|
'tenancy_db_name' => 'db' . Str::random(16),
|
||||||
|
]);
|
||||||
|
migrateTenants();
|
||||||
|
$user = $tenant->run(function () {
|
||||||
|
return ImpersonationUser::create([
|
||||||
|
'name' => 'Joe',
|
||||||
|
'email' => 'joe@local',
|
||||||
|
'password' => bcrypt('secret'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// We try to visit the dashboard directly, before impersonating the user.
|
||||||
|
$this->get('/acme/dashboard')
|
||||||
|
->assertRedirect('/login');
|
||||||
|
|
||||||
|
// We impersonate the user
|
||||||
|
$token = tenancy()->impersonate($tenant, $user->id, '/acme/dashboard');
|
||||||
|
$this->get('/acme/impersonate/' . $token->token)
|
||||||
|
->assertRedirect('/acme/dashboard');
|
||||||
|
|
||||||
|
// Now we try to visit the dashboard directly, after impersonating the user.
|
||||||
|
$this->get('/acme/dashboard')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('You are logged in as Joe');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tokens have a limited ttl', function () {
|
||||||
|
Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'foo.localhost',
|
||||||
|
]);
|
||||||
|
migrateTenants();
|
||||||
|
$user = $tenant->run(function () {
|
||||||
|
return ImpersonationUser::create([
|
||||||
|
'name' => 'Joe',
|
||||||
|
'email' => 'joe@local',
|
||||||
|
'password' => bcrypt('secret'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// We impersonate the user
|
||||||
|
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
||||||
|
$token->update([
|
||||||
|
'created_at' => Carbon::now()->subtract(CarbonInterval::make('100s')),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->followingRedirects()
|
||||||
|
->get('http://foo.localhost/impersonate/' . $token->token)
|
||||||
|
->assertStatus(403);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tokens are deleted after use', function () {
|
||||||
|
Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'foo.localhost',
|
||||||
|
]);
|
||||||
|
migrateTenants();
|
||||||
|
$user = $tenant->run(function () {
|
||||||
|
return ImpersonationUser::create([
|
||||||
|
'name' => 'Joe',
|
||||||
|
'email' => 'joe@local',
|
||||||
|
'password' => bcrypt('secret'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// We impersonate the user
|
||||||
|
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
||||||
|
|
||||||
|
$this->assertNotNull(ImpersonationToken::find($token->token));
|
||||||
|
|
||||||
|
$this->followingRedirects()
|
||||||
|
->get('http://foo.localhost/impersonate/' . $token->token)
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('You are logged in as Joe');
|
||||||
|
|
||||||
|
expect(ImpersonationToken::find($token->token))->toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('impersonation works with multiple models and guards', function () {
|
||||||
|
config([
|
||||||
|
'auth.guards.another' => [
|
||||||
|
'driver' => 'session',
|
||||||
|
'provider' => 'another_users',
|
||||||
|
],
|
||||||
|
'auth.providers.another_users' => [
|
||||||
|
'driver' => 'eloquent',
|
||||||
|
'model' => AnotherImpersonationUser::class,
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
Auth::extend('another', function ($app, $name, array $config) {
|
||||||
|
return new SessionGuard($name, Auth::createUserProvider($config['provider']), session());
|
||||||
|
});
|
||||||
|
|
||||||
|
Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes(true, 'another'));
|
||||||
|
|
||||||
|
$tenant = Tenant::create();
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'foo.localhost',
|
||||||
|
]);
|
||||||
|
migrateTenants();
|
||||||
|
$user = $tenant->run(function () {
|
||||||
|
return AnotherImpersonationUser::create([
|
||||||
|
'name' => 'Joe',
|
||||||
|
'email' => 'joe@local',
|
||||||
|
'password' => bcrypt('secret'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// We try to visit the dashboard directly, before impersonating the user.
|
||||||
|
$this->get('http://foo.localhost/dashboard')
|
||||||
|
->assertRedirect('http://foo.localhost/login');
|
||||||
|
|
||||||
|
// We impersonate the user
|
||||||
|
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard', 'another');
|
||||||
|
$this->get('http://foo.localhost/impersonate/' . $token->token)
|
||||||
|
->assertRedirect('http://foo.localhost/dashboard');
|
||||||
|
|
||||||
|
// Now we try to visit the dashboard directly, after impersonating the user.
|
||||||
|
$this->get('http://foo.localhost/dashboard')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('You are logged in as Joe');
|
||||||
|
|
||||||
|
Tenant::first()->run(function () {
|
||||||
|
expect(auth()->guard('another')->user()->name)->toBe('Joe');
|
||||||
|
expect(auth()->guard('web')->user())->toBe(null);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function migrateTenants()
|
||||||
{
|
{
|
||||||
protected function migrateTenants()
|
test()->artisan('tenants:migrate')->assertExitCode(0);
|
||||||
{
|
}
|
||||||
$this->artisan('tenants:migrate')->assertExitCode(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function setUp(): void
|
function makeLoginRoute()
|
||||||
{
|
{
|
||||||
parent::setUp();
|
Route::get('/login', function () {
|
||||||
|
return 'Please log in';
|
||||||
|
})->name('login');
|
||||||
|
}
|
||||||
|
|
||||||
$this->artisan('migrate', [
|
function getRoutes($loginRoute = true, $authGuard = 'web'): Closure
|
||||||
'--path' => __DIR__ . '/../assets/impersonation-migrations',
|
{
|
||||||
'--realpath' => true,
|
return function () use ($loginRoute, $authGuard) {
|
||||||
])->assertExitCode(0);
|
if ($loginRoute) {
|
||||||
|
test()->makeLoginRoute();
|
||||||
|
}
|
||||||
|
|
||||||
config([
|
Route::get('/dashboard', function () use ($authGuard) {
|
||||||
'tenancy.bootstrappers' => [
|
return 'You are logged in as ' . auth()->guard($authGuard)->user()->name;
|
||||||
DatabaseTenancyBootstrapper::class,
|
})->middleware('auth:' . $authGuard);
|
||||||
],
|
|
||||||
'tenancy.features' => [
|
|
||||||
UserImpersonation::class,
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
Event::listen(
|
Route::get('/impersonate/{token}', function ($token) {
|
||||||
TenantCreated::class,
|
return UserImpersonation::makeResponse($token);
|
||||||
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
|
|
||||||
return $event->tenant;
|
|
||||||
})->toListener()
|
|
||||||
);
|
|
||||||
|
|
||||||
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
|
|
||||||
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
|
|
||||||
|
|
||||||
config(['auth.providers.users.model' => ImpersonationUser::class]);
|
|
||||||
}
|
|
||||||
|
|
||||||
public function makeLoginRoute()
|
|
||||||
{
|
|
||||||
Route::get('/login', function () {
|
|
||||||
return 'Please log in';
|
|
||||||
})->name('login');
|
|
||||||
}
|
|
||||||
|
|
||||||
public function getRoutes($loginRoute = true, $authGuard = 'web'): Closure
|
|
||||||
{
|
|
||||||
return function () use ($loginRoute, $authGuard) {
|
|
||||||
if ($loginRoute) {
|
|
||||||
$this->makeLoginRoute();
|
|
||||||
}
|
|
||||||
|
|
||||||
Route::get('/dashboard', function () use ($authGuard) {
|
|
||||||
return 'You are logged in as ' . auth()->guard($authGuard)->user()->name;
|
|
||||||
})->middleware('auth:' . $authGuard);
|
|
||||||
|
|
||||||
Route::get('/impersonate/{token}', function ($token) {
|
|
||||||
return UserImpersonation::makeResponse($token);
|
|
||||||
});
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_user_can_be_impersonated_on_a_tenant_domain()
|
|
||||||
{
|
|
||||||
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'foo.localhost',
|
|
||||||
]);
|
|
||||||
$this->migrateTenants();
|
|
||||||
$user = $tenant->run(function () {
|
|
||||||
return ImpersonationUser::create([
|
|
||||||
'name' => 'Joe',
|
|
||||||
'email' => 'joe@local',
|
|
||||||
'password' => bcrypt('secret'),
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
};
|
||||||
// We try to visit the dashboard directly, before impersonating the user.
|
|
||||||
$this->get('http://foo.localhost/dashboard')
|
|
||||||
->assertRedirect('http://foo.localhost/login');
|
|
||||||
|
|
||||||
// We impersonate the user
|
|
||||||
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
|
||||||
$this->get('http://foo.localhost/impersonate/' . $token->token)
|
|
||||||
->assertRedirect('http://foo.localhost/dashboard');
|
|
||||||
|
|
||||||
// Now we try to visit the dashboard directly, after impersonating the user.
|
|
||||||
$this->get('http://foo.localhost/dashboard')
|
|
||||||
->assertSuccessful()
|
|
||||||
->assertSee('You are logged in as Joe');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tenant_user_can_be_impersonated_on_a_tenant_path()
|
|
||||||
{
|
|
||||||
$this->makeLoginRoute();
|
|
||||||
|
|
||||||
Route::middleware(InitializeTenancyByPath::class)->prefix('/{tenant}')->group($this->getRoutes(false));
|
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
|
||||||
'id' => 'acme',
|
|
||||||
'tenancy_db_name' => 'db' . Str::random(16),
|
|
||||||
]);
|
|
||||||
$this->migrateTenants();
|
|
||||||
$user = $tenant->run(function () {
|
|
||||||
return ImpersonationUser::create([
|
|
||||||
'name' => 'Joe',
|
|
||||||
'email' => 'joe@local',
|
|
||||||
'password' => bcrypt('secret'),
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// We try to visit the dashboard directly, before impersonating the user.
|
|
||||||
$this->get('/acme/dashboard')
|
|
||||||
->assertRedirect('/login');
|
|
||||||
|
|
||||||
// We impersonate the user
|
|
||||||
$token = tenancy()->impersonate($tenant, $user->id, '/acme/dashboard');
|
|
||||||
$this->get('/acme/impersonate/' . $token->token)
|
|
||||||
->assertRedirect('/acme/dashboard');
|
|
||||||
|
|
||||||
// Now we try to visit the dashboard directly, after impersonating the user.
|
|
||||||
$this->get('/acme/dashboard')
|
|
||||||
->assertSuccessful()
|
|
||||||
->assertSee('You are logged in as Joe');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tokens_have_a_limited_ttl()
|
|
||||||
{
|
|
||||||
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'foo.localhost',
|
|
||||||
]);
|
|
||||||
$this->migrateTenants();
|
|
||||||
$user = $tenant->run(function () {
|
|
||||||
return ImpersonationUser::create([
|
|
||||||
'name' => 'Joe',
|
|
||||||
'email' => 'joe@local',
|
|
||||||
'password' => bcrypt('secret'),
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// We impersonate the user
|
|
||||||
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
|
||||||
$token->update([
|
|
||||||
'created_at' => Carbon::now()->subtract(CarbonInterval::make('100s')),
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->followingRedirects()
|
|
||||||
->get('http://foo.localhost/impersonate/' . $token->token)
|
|
||||||
->assertStatus(403);
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function tokens_are_deleted_after_use()
|
|
||||||
{
|
|
||||||
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'foo.localhost',
|
|
||||||
]);
|
|
||||||
$this->migrateTenants();
|
|
||||||
$user = $tenant->run(function () {
|
|
||||||
return ImpersonationUser::create([
|
|
||||||
'name' => 'Joe',
|
|
||||||
'email' => 'joe@local',
|
|
||||||
'password' => bcrypt('secret'),
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// We impersonate the user
|
|
||||||
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard');
|
|
||||||
|
|
||||||
$this->assertNotNull(ImpersonationToken::find($token->token));
|
|
||||||
|
|
||||||
$this->followingRedirects()
|
|
||||||
->get('http://foo.localhost/impersonate/' . $token->token)
|
|
||||||
->assertSuccessful()
|
|
||||||
->assertSee('You are logged in as Joe');
|
|
||||||
|
|
||||||
$this->assertNull(ImpersonationToken::find($token->token));
|
|
||||||
}
|
|
||||||
|
|
||||||
/** @test */
|
|
||||||
public function impersonation_works_with_multiple_models_and_guards()
|
|
||||||
{
|
|
||||||
config([
|
|
||||||
'auth.guards.another' => [
|
|
||||||
'driver' => 'session',
|
|
||||||
'provider' => 'another_users',
|
|
||||||
],
|
|
||||||
'auth.providers.another_users' => [
|
|
||||||
'driver' => 'eloquent',
|
|
||||||
'model' => AnotherImpersonationUser::class,
|
|
||||||
],
|
|
||||||
]);
|
|
||||||
|
|
||||||
Auth::extend('another', function ($app, $name, array $config) {
|
|
||||||
return new SessionGuard($name, Auth::createUserProvider($config['provider']), session());
|
|
||||||
});
|
|
||||||
|
|
||||||
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes(true, 'another'));
|
|
||||||
|
|
||||||
$tenant = Tenant::create();
|
|
||||||
$tenant->domains()->create([
|
|
||||||
'domain' => 'foo.localhost',
|
|
||||||
]);
|
|
||||||
$this->migrateTenants();
|
|
||||||
$user = $tenant->run(function () {
|
|
||||||
return AnotherImpersonationUser::create([
|
|
||||||
'name' => 'Joe',
|
|
||||||
'email' => 'joe@local',
|
|
||||||
'password' => bcrypt('secret'),
|
|
||||||
]);
|
|
||||||
});
|
|
||||||
|
|
||||||
// We try to visit the dashboard directly, before impersonating the user.
|
|
||||||
$this->get('http://foo.localhost/dashboard')
|
|
||||||
->assertRedirect('http://foo.localhost/login');
|
|
||||||
|
|
||||||
// We impersonate the user
|
|
||||||
$token = tenancy()->impersonate($tenant, $user->id, '/dashboard', 'another');
|
|
||||||
$this->get('http://foo.localhost/impersonate/' . $token->token)
|
|
||||||
->assertRedirect('http://foo.localhost/dashboard');
|
|
||||||
|
|
||||||
// Now we try to visit the dashboard directly, after impersonating the user.
|
|
||||||
$this->get('http://foo.localhost/dashboard')
|
|
||||||
->assertSuccessful()
|
|
||||||
->assertSee('You are logged in as Joe');
|
|
||||||
|
|
||||||
Tenant::first()->run(function () {
|
|
||||||
$this->assertSame('Joe', auth()->guard('another')->user()->name);
|
|
||||||
$this->assertSame(null, auth()->guard('web')->user());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
class ImpersonationUser extends Authenticable
|
class ImpersonationUser extends Authenticable
|
||||||
|
|
|
||||||
|
|
@ -2,65 +2,76 @@
|
||||||
|
|
||||||
declare(strict_types=1);
|
declare(strict_types=1);
|
||||||
|
|
||||||
namespace Stancl\Tenancy\Tests;
|
|
||||||
|
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
use Stancl\Tenancy\Features\UniversalRoutes;
|
use Stancl\Tenancy\Features\UniversalRoutes;
|
||||||
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
|
||||||
use Stancl\Tenancy\Tests\Etc\Tenant;
|
use Stancl\Tenancy\Tests\Etc\Tenant;
|
||||||
|
|
||||||
class UniversalRouteTest extends TestCase
|
afterEach(function () {
|
||||||
{
|
InitializeTenancyByDomain::$onFail = null;
|
||||||
public function tearDown(): void
|
});
|
||||||
{
|
|
||||||
InitializeTenancyByDomain::$onFail = null;
|
|
||||||
|
|
||||||
parent::tearDown();
|
test('a route can work in both central and tenant context', function () {
|
||||||
}
|
Route::middlewareGroup('universal', []);
|
||||||
|
config(['tenancy.features' => [UniversalRoutes::class]]);
|
||||||
|
|
||||||
/** @test */
|
Route::get('/foo', function () {
|
||||||
public function a_route_can_work_in_both_central_and_tenant_context()
|
return tenancy()->initialized
|
||||||
{
|
? 'Tenancy is initialized.'
|
||||||
Route::middlewareGroup('universal', []);
|
: 'Tenancy is not initialized.';
|
||||||
config(['tenancy.features' => [UniversalRoutes::class]]);
|
})->middleware(['universal', InitializeTenancyByDomain::class]);
|
||||||
|
|
||||||
Route::get('/foo', function () {
|
$this->get('http://localhost/foo')
|
||||||
return tenancy()->initialized
|
->assertSuccessful()
|
||||||
? 'Tenancy is initialized.'
|
->assertSee('Tenancy is not initialized.');
|
||||||
: 'Tenancy is not initialized.';
|
|
||||||
})->middleware(['universal', InitializeTenancyByDomain::class]);
|
|
||||||
|
|
||||||
$this->get('http://localhost/foo')
|
$tenant = Tenant::create([
|
||||||
->assertSuccessful()
|
'id' => 'acme',
|
||||||
->assertSee('Tenancy is not initialized.');
|
]);
|
||||||
|
$tenant->domains()->create([
|
||||||
|
'domain' => 'acme.localhost',
|
||||||
|
]);
|
||||||
|
|
||||||
$tenant = Tenant::create([
|
$this->get('http://acme.localhost/foo')
|
||||||
'id' => 'acme',
|
->assertSuccessful()
|
||||||
]);
|
->assertSee('Tenancy is initialized.');
|
||||||
$tenant->domains()->create([
|
});
|
||||||
'domain' => 'acme.localhost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
$this->get('http://acme.localhost/foo')
|
test('making one route universal doesnt make all routes universal', function () {
|
||||||
->assertSuccessful()
|
Route::get('/bar', function () {
|
||||||
->assertSee('Tenancy is initialized.');
|
return tenant('id');
|
||||||
}
|
})->middleware(InitializeTenancyByDomain::class);
|
||||||
|
|
||||||
/** @test */
|
Route::middlewareGroup('universal', []);
|
||||||
public function making_one_route_universal_doesnt_make_all_routes_universal()
|
config(['tenancy.features' => [UniversalRoutes::class]]);
|
||||||
{
|
|
||||||
Route::get('/bar', function () {
|
|
||||||
return tenant('id');
|
|
||||||
})->middleware(InitializeTenancyByDomain::class);
|
|
||||||
|
|
||||||
$this->a_route_can_work_in_both_central_and_tenant_context();
|
Route::get('/foo', function () {
|
||||||
tenancy()->end();
|
return tenancy()->initialized
|
||||||
|
? 'Tenancy is initialized.'
|
||||||
|
: 'Tenancy is not initialized.';
|
||||||
|
})->middleware(['universal', InitializeTenancyByDomain::class]);
|
||||||
|
|
||||||
$this->get('http://localhost/bar')
|
$this->get('http://localhost/foo')
|
||||||
->assertStatus(500);
|
->assertSuccessful()
|
||||||
|
->assertSee('Tenancy is not initialized.');
|
||||||
|
|
||||||
$this->get('http://acme.localhost/bar')
|
$tenant = Tenant::create([
|
||||||
->assertSuccessful()
|
'id' => 'acme',
|
||||||
->assertSee('acme');
|
]);
|
||||||
}
|
$tenant->domains()->create([
|
||||||
}
|
'domain' => 'acme.localhost',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->get('http://acme.localhost/foo')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('Tenancy is initialized.');
|
||||||
|
|
||||||
|
tenancy()->end();
|
||||||
|
|
||||||
|
$this->get('http://localhost/bar')
|
||||||
|
->assertStatus(500);
|
||||||
|
|
||||||
|
$this->get('http://acme.localhost/bar')
|
||||||
|
->assertSuccessful()
|
||||||
|
->assertSee('acme');
|
||||||
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue