1
0
Fork 0
mirror of https://github.com/archtechx/tenancy.git synced 2025-12-12 13:54: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:
Samuel Štancl 2022-07-22 19:26:59 +02:00 committed by GitHub
parent 69de181b7d
commit b47c5549ef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
32 changed files with 3010 additions and 3478 deletions

View file

@ -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
View file

@ -1,3 +1,3 @@
#!/bin/bash #!/bin/bash
docker-compose exec -T test vendor/bin/phpunit "$@" docker-compose exec -T test vendor/bin/pest "$@"

View file

@ -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,45 +10,24 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
} });
/** @test */ test('context is switched when tenancy is initialized', function () {
public function context_is_switched_when_tenancy_is_initialized() contextIsSwitchedWhenTenancyInitialized();
{ });
config(['tenancy.bootstrappers' => [
MyBootstrapper::class,
]]);
$tenant = Tenant::create([ test('context is reverted when tenancy is ended', function () {
'id' => 'acme', contextIsSwitchedWhenTenancyInitialized();
]);
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(); tenancy()->end();
$this->assertSame(true, app('tenancy_ended')); expect(app('tenancy_ended'))->toBe(true);
} });
/** @test */ test('context is switched when tenancy is reinitialized', function () {
public function context_is_switched_when_tenancy_is_reinitialized()
{
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
MyBootstrapper::class, MyBootstrapper::class,
]]); ]]);
@ -61,7 +38,7 @@ class AutomaticModeTest extends TestCase
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame('acme', app('tenancy_initialized_for_tenant')); expect(app('tenancy_initialized_for_tenant'))->toBe('acme');
$tenant2 = Tenant::create([ $tenant2 = Tenant::create([
'id' => 'foobar', 'id' => 'foobar',
@ -69,56 +46,63 @@ class AutomaticModeTest extends TestCase
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertSame('foobar', app('tenancy_initialized_for_tenant')); expect(app('tenancy_initialized_for_tenant'))->toBe('foobar');
} });
/** @test */ test('central helper runs callbacks in the central state', function () {
public function central_helper_runs_callbacks_in_the_central_state()
{
tenancy()->initialize($tenant = Tenant::create()); tenancy()->initialize($tenant = Tenant::create());
tenancy()->central(function () { tenancy()->central(function () {
$this->assertSame(null, tenant()); expect(tenant())->toBe(null);
}); });
$this->assertSame($tenant, tenant()); expect(tenant())->toBe($tenant);
} });
/** @test */ test('central helper returns the value from the callback', function () {
public function central_helper_returns_the_value_from_the_callback()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$this->assertSame('foo', tenancy()->central(function () { $this->assertSame('foo', tenancy()->central(function () {
return 'foo'; return 'foo';
})); }));
} });
/** @test */ test('central helper reverts back to tenant context', function () {
public function central_helper_reverts_back_to_tenant_context()
{
tenancy()->initialize($tenant = Tenant::create()); tenancy()->initialize($tenant = Tenant::create());
tenancy()->central(function () { tenancy()->central(function () {
// //
}); });
$this->assertSame($tenant, tenant()); expect(tenant())->toBe($tenant);
} });
/** @test */ test('central helper doesnt change tenancy state when called in central context', function () {
public function central_helper_doesnt_change_tenancy_state_when_called_in_central_context() expect(tenancy()->initialized)->toBeFalse();
{ expect(tenant())->toBeNull();
$this->assertFalse(tenancy()->initialized);
$this->assertNull(tenant());
tenancy()->central(function () { tenancy()->central(function () {
// //
}); });
$this->assertFalse(tenancy()->initialized); expect(tenancy()->initialized)->toBeFalse();
$this->assertNull(tenant()); expect(tenant())->toBeNull();
} });
// todo@tests
function contextIsSwitchedWhenTenancyInitialized()
{
config(['tenancy.bootstrappers' => [
MyBootstrapper::class,
]]);
$tenant = Tenant::create([
'id' => 'acme',
]);
tenancy()->initialize($tenant);
expect(app('tenancy_initialized_for_tenant'))->toBe('acme');
} }
class MyBootstrapper implements TenancyBootstrapper class MyBootstrapper implements TenancyBootstrapper

View file

@ -2,38 +2,27 @@
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;
class BootstrapperTest extends TestCase use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
{ use Stancl\Tenancy\Bootstrappers\FilesystemTenancyBootstrapper;
public $mockConsoleOutput = false;
public function setUp(): void
{
parent::setUp();
beforeEach(function () {
Event::listen( Event::listen(
TenantCreated::class, TenantCreated::class,
JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) { JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
@ -43,11 +32,9 @@ class BootstrapperTest extends TestCase
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
} });
/** @test */ test('database data is separated', function () {
public function database_data_is_separated()
{
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class, DatabaseTenancyBootstrapper::class,
]]); ]]);
@ -61,26 +48,24 @@ class BootstrapperTest extends TestCase
// Create Foo user // Create Foo user
DB::table('users')->insert(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']); DB::table('users')->insert(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
$this->assertCount(1, DB::table('users')->get()); expect(DB::table('users')->get())->toHaveCount(1);
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
// Assert Foo user is not in this DB // Assert Foo user is not in this DB
$this->assertCount(0, DB::table('users')->get()); expect(DB::table('users')->get())->toHaveCount(0);
// Create Bar user // Create Bar user
DB::table('users')->insert(['name' => 'Bar', 'email' => 'bar@bar.com', 'password' => 'secret']); DB::table('users')->insert(['name' => 'Bar', 'email' => 'bar@bar.com', 'password' => 'secret']);
$this->assertCount(1, DB::table('users')->get()); expect(DB::table('users')->get())->toHaveCount(1);
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
// Assert Bar user is not in this DB // Assert Bar user is not in this DB
$this->assertCount(1, DB::table('users')->get()); expect(DB::table('users')->get())->toHaveCount(1);
$this->assertSame('Foo', DB::table('users')->first()->name); expect(DB::table('users')->first()->name)->toBe('Foo');
} });
/** @test */ test('cache data is separated', function () {
public function cache_data_is_separated()
{
config([ config([
'tenancy.bootstrappers' => [ 'tenancy.bootstrappers' => [
CacheTenancyBootstrapper::class, CacheTenancyBootstrapper::class,
@ -92,38 +77,36 @@ class BootstrapperTest extends TestCase
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
cache()->set('foo', 'central'); cache()->set('foo', 'central');
$this->assertSame('central', Cache::get('foo')); expect(Cache::get('foo'))->toBe('central');
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
// Assert central cache doesn't leak to tenant context // Assert central cache doesn't leak to tenant context
$this->assertFalse(Cache::has('foo')); expect(Cache::has('foo'))->toBeFalse();
cache()->set('foo', 'bar'); cache()->set('foo', 'bar');
$this->assertSame('bar', Cache::get('foo')); expect(Cache::get('foo'))->toBe('bar');
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
// Assert one tenant's data doesn't leak to another tenant // Assert one tenant's data doesn't leak to another tenant
$this->assertFalse(Cache::has('foo')); expect(Cache::has('foo'))->toBeFalse();
cache()->set('foo', 'xyz'); cache()->set('foo', 'xyz');
$this->assertSame('xyz', Cache::get('foo')); expect(Cache::get('foo'))->toBe('xyz');
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
// Asset data didn't leak to original tenant // Asset data didn't leak to original tenant
$this->assertSame('bar', Cache::get('foo')); expect(Cache::get('foo'))->toBe('bar');
tenancy()->end(); tenancy()->end();
// Asset central is still the same // Asset central is still the same
$this->assertSame('central', Cache::get('foo')); expect(Cache::get('foo'))->toBe('central');
} });
/** @test */ test('redis data is separated', function () {
public function redis_data_is_separated()
{
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
RedisTenancyBootstrapper::class, RedisTenancyBootstrapper::class,
]]); ]]);
@ -133,28 +116,26 @@ class BootstrapperTest extends TestCase
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
Redis::set('foo', 'bar'); Redis::set('foo', 'bar');
$this->assertSame('bar', Redis::get('foo')); expect(Redis::get('foo'))->toBe('bar');
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertSame(null, Redis::get('foo')); expect(Redis::get('foo'))->toBe(null);
Redis::set('foo', 'xyz'); Redis::set('foo', 'xyz');
Redis::set('abc', 'def'); Redis::set('abc', 'def');
$this->assertSame('xyz', Redis::get('foo')); expect(Redis::get('foo'))->toBe('xyz');
$this->assertSame('def', Redis::get('abc')); expect(Redis::get('abc'))->toBe('def');
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('bar', Redis::get('foo')); expect(Redis::get('foo'))->toBe('bar');
$this->assertSame(null, Redis::get('abc')); expect(Redis::get('abc'))->toBe(null);
$tenant3 = Tenant::create(); $tenant3 = Tenant::create();
tenancy()->initialize($tenant3); tenancy()->initialize($tenant3);
$this->assertSame(null, Redis::get('foo')); expect(Redis::get('foo'))->toBe(null);
$this->assertSame(null, Redis::get('abc')); expect(Redis::get('abc'))->toBe(null);
} });
/** @test */ test('filesystem data is separated', function () {
public function filesystem_data_is_separated()
{
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
FilesystemTenancyBootstrapper::class, FilesystemTenancyBootstrapper::class,
]]); ]]);
@ -171,37 +152,37 @@ class BootstrapperTest extends TestCase
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
Storage::disk('public')->put('foo', 'bar'); Storage::disk('public')->put('foo', 'bar');
$this->assertSame('bar', Storage::disk('public')->get('foo')); expect(Storage::disk('public')->get('foo'))->toBe('bar');
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertFalse(Storage::disk('public')->exists('foo')); expect(Storage::disk('public')->exists('foo'))->toBeFalse();
Storage::disk('public')->put('foo', 'xyz'); Storage::disk('public')->put('foo', 'xyz');
Storage::disk('public')->put('abc', 'def'); Storage::disk('public')->put('abc', 'def');
$this->assertSame('xyz', Storage::disk('public')->get('foo')); expect(Storage::disk('public')->get('foo'))->toBe('xyz');
$this->assertSame('def', Storage::disk('public')->get('abc')); expect(Storage::disk('public')->get('abc'))->toBe('def');
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('bar', Storage::disk('public')->get('foo')); expect(Storage::disk('public')->get('foo'))->toBe('bar');
$this->assertFalse(Storage::disk('public')->exists('abc')); expect(Storage::disk('public')->exists('abc'))->toBeFalse();
$tenant3 = Tenant::create(); $tenant3 = Tenant::create();
tenancy()->initialize($tenant3); tenancy()->initialize($tenant3);
$this->assertFalse(Storage::disk('public')->exists('foo')); expect(Storage::disk('public')->exists('foo'))->toBeFalse();
$this->assertFalse(Storage::disk('public')->exists('abc')); expect(Storage::disk('public')->exists('abc'))->toBeFalse();
$expected_storage_path = $old_storage_path . '/tenant' . tenant('id'); // /tenant = suffix base $expected_storage_path = $old_storage_path . '/tenant' . tenant('id'); // /tenant = suffix base
// Check that disk prefixes respect the root_override logic // Check that disk prefixes respect the root_override logic
$this->assertSame($expected_storage_path . '/app/', $this->getDiskPrefix('local')); expect(getDiskPrefix('local'))->toBe($expected_storage_path . '/app/');
$this->assertSame($expected_storage_path . '/app/public/', $this->getDiskPrefix('public')); expect(getDiskPrefix('public'))->toBe($expected_storage_path . '/app/public/');
$this->assertSame('tenant' . tenant('id') . '/', $this->getDiskPrefix('s3'), '/'); $this->assertSame('tenant' . tenant('id') . '/', getDiskPrefix('s3'), '/');
// Check suffixing logic // Check suffixing logic
$new_storage_path = storage_path(); $new_storage_path = storage_path();
$this->assertEquals($expected_storage_path, $new_storage_path); expect($new_storage_path)->toEqual($expected_storage_path);
} });
protected function getDiskPrefix(string $disk): string function getDiskPrefix(string $disk): string
{ {
/** @var FilesystemAdapter $disk */ /** @var FilesystemAdapter $disk */
$disk = Storage::disk($disk); $disk = Storage::disk($disk);
@ -222,6 +203,3 @@ class BootstrapperTest extends TestCase
return $prefix->getValue($prefixer); return $prefix->getValue($prefixer);
} }
// for queues see QueueTest
}

View file

@ -2,79 +2,60 @@
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 () {
{
public function setUp(): void
{
parent::setUp();
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
CacheTenancyBootstrapper::class, CacheTenancyBootstrapper::class,
]]); ]]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
} });
/** @test */ test('default tag is automatically applied', function () {
public function default_tag_is_automatically_applied()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$this->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames()); $this->assertArrayIsSubset([config('tenancy.cache.tag_base') . tenant('id')], cache()->tags('foo')->getTags()->getNames());
} });
/** @test */ test('tags are merged when array is passed', function () {
public function tags_are_merged_when_array_is_passed()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar']; $expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo', 'bar'];
$this->assertEquals($expected, cache()->tags(['foo', 'bar'])->getTags()->getNames()); expect(cache()->tags(['foo', 'bar'])->getTags()->getNames())->toEqual($expected);
} });
/** @test */ test('tags are merged when string is passed', function () {
public function tags_are_merged_when_string_is_passed()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo']; $expected = [config('tenancy.cache.tag_base') . tenant('id'), 'foo'];
$this->assertEquals($expected, cache()->tags('foo')->getTags()->getNames()); expect(cache()->tags('foo')->getTags()->getNames())->toEqual($expected);
} });
/** @test */ test('exception is thrown when zero arguments are passed to tags method', function () {
public function exception_is_thrown_when_zero_arguments_are_passed_to_tags_method()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
cache()->tags(); cache()->tags();
} });
/** @test */ test('exception is thrown when more than one argument is passed to tags method', function () {
public function exception_is_thrown_when_more_than_one_argument_is_passed_to_tags_method()
{
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$this->expectException(\Exception::class); $this->expectException(\Exception::class);
cache()->tags(1, 2); cache()->tags(1, 2);
} });
/** @test */ test('tags separate cache well enough', function () {
public function tags_separate_cache_well_enough()
{
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
cache()->put('foo', 'bar', 1); cache()->put('foo', 'bar', 1);
$this->assertSame('bar', cache()->get('foo')); expect(cache()->get('foo'))->toBe('bar');
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
@ -82,17 +63,15 @@ class CacheManagerTest extends TestCase
$this->assertNotSame('bar', cache()->get('foo')); $this->assertNotSame('bar', cache()->get('foo'));
cache()->put('foo', 'xyz', 1); cache()->put('foo', 'xyz', 1);
$this->assertSame('xyz', cache()->get('foo')); expect(cache()->get('foo'))->toBe('xyz');
} });
/** @test */ test('invoking the cache helper works', function () {
public function invoking_the_cache_helper_works()
{
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
cache(['foo' => 'bar'], 1); cache(['foo' => 'bar'], 1);
$this->assertSame('bar', cache('foo')); expect(cache('foo'))->toBe('bar');
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
@ -100,38 +79,33 @@ class CacheManagerTest extends TestCase
$this->assertNotSame('bar', cache('foo')); $this->assertNotSame('bar', cache('foo'));
cache(['foo' => 'xyz'], 1); cache(['foo' => 'xyz'], 1);
$this->assertSame('xyz', cache('foo')); expect(cache('foo'))->toBe('xyz');
} });
/** @test */ test('cache is persisted', function () {
public function cache_is_persisted()
{
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
cache(['foo' => 'bar'], 10); cache(['foo' => 'bar'], 10);
$this->assertSame('bar', cache('foo')); expect(cache('foo'))->toBe('bar');
tenancy()->end(); tenancy()->end();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('bar', cache('foo')); expect(cache('foo'))->toBe('bar');
} });
/** @test */ test('cache is persisted when reidentification is used', function () {
public function cache_is_persisted_when_reidentification_is_used()
{
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
cache(['foo' => 'bar'], 10); cache(['foo' => 'bar'], 10);
$this->assertSame('bar', cache('foo')); expect(cache('foo'))->toBe('bar');
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
tenancy()->end(); tenancy()->end();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('bar', cache('foo')); expect(cache('foo'))->toBe('bar');
} });
}

View file

@ -2,36 +2,24 @@
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 () {
{
public function tearDown(): void
{
DomainTenantResolver::$shouldCache = false; DomainTenantResolver::$shouldCache = false;
});
parent::tearDown(); test('tenants can be resolved using the cached resolver', function () {
}
/** @test */
public function tenants_can_be_resolved_using_the_cached_resolver()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'acme', 'domain' => 'acme',
]); ]);
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue()->toBeTrue();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); });
}
/** @test */ test('the underlying resolver is not touched when using the cached resolver', function () {
public function the_underlying_resolver_is_not_touched_when_using_the_cached_resolver()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'acme', 'domain' => 'acme',
@ -41,22 +29,20 @@ class CachedTenantResolverTest extends TestCase
DomainTenantResolver::$shouldCache = false; DomainTenantResolver::$shouldCache = false;
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty $this->assertNotEmpty(DB::getQueryLog()); // not empty
DomainTenantResolver::$shouldCache = true; DomainTenantResolver::$shouldCache = true;
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertEmpty(DB::getQueryLog()); // empty expect(DB::getQueryLog())->toBeEmpty(); // empty
} });
/** @test */ test('cache is invalidated when the tenant is updated', function () {
public function cache_is_invalidated_when_the_tenant_is_updated()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->createDomain([ $tenant->createDomain([
'domain' => 'acme', 'domain' => 'acme',
@ -66,23 +52,21 @@ class CachedTenantResolverTest extends TestCase
DomainTenantResolver::$shouldCache = true; DomainTenantResolver::$shouldCache = true;
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertEmpty(DB::getQueryLog()); // empty expect(DB::getQueryLog())->toBeEmpty(); // empty
$tenant->update([ $tenant->update([
'foo' => 'bar', 'foo' => 'bar',
]); ]);
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty $this->assertNotEmpty(DB::getQueryLog()); // not empty
} });
/** @test */ test('cache is invalidated when a tenants domain is changed', function () {
public function cache_is_invalidated_when_a_tenants_domain_is_changed()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->createDomain([ $tenant->createDomain([
'domain' => 'acme', 'domain' => 'acme',
@ -92,21 +76,20 @@ class CachedTenantResolverTest extends TestCase
DomainTenantResolver::$shouldCache = true; DomainTenantResolver::$shouldCache = true;
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertEmpty(DB::getQueryLog()); // empty expect(DB::getQueryLog())->toBeEmpty(); // empty
$tenant->createDomain([ $tenant->createDomain([
'domain' => 'bar', 'domain' => 'bar',
]); ]);
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('acme'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('acme')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty $this->assertNotEmpty(DB::getQueryLog()); // not empty
DB::flushQueryLog(); DB::flushQueryLog();
$this->assertTrue($tenant->is(app(DomainTenantResolver::class)->resolve('bar'))); expect($tenant->is(app(DomainTenantResolver::class)->resolve('bar')))->toBeTrue();
$this->assertNotEmpty(DB::getQueryLog()); // not empty $this->assertNotEmpty(DB::getQueryLog()); // not empty
} });
}

View file

@ -2,19 +2,12 @@
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 () {
{
public function setUp(): void
{
parent::setUp();
Route::group([ Route::group([
'middleware' => InitializeTenancyByDomainOrSubdomain::class, 'middleware' => InitializeTenancyByDomainOrSubdomain::class,
], function () { ], function () {
@ -24,11 +17,9 @@ class CombinedDomainAndSubdomainIdentificationTest extends TestCase
}); });
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([
@ -39,19 +30,17 @@ class CombinedDomainAndSubdomainIdentificationTest extends TestCase
'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([
@ -62,16 +51,15 @@ class CombinedDomainAndSubdomainIdentificationTest extends TestCase
'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
{ {

View file

@ -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,12 +17,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
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());
@ -35,156 +28,111 @@ class CommandsTest extends TestCase
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
} });
public function tearDown(): void
{
parent::tearDown();
afterEach(function () {
// Cleanup tenancy config cache // Cleanup tenancy config cache
if (file_exists(base_path('config/tenancy.php'))) { if (file_exists(base_path('config/tenancy.php'))) {
unlink(base_path('config/tenancy.php')); unlink(base_path('config/tenancy.php'));
} }
} });
/** @test */ test('migrate command doesnt change the db connection', function () {
public function migrate_command_doesnt_change_the_db_connection() expect(Schema::hasTable('users'))->toBeFalse();
{
$this->assertFalse(Schema::hasTable('users'));
$old_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName(); $old_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
Artisan::call('tenants:migrate'); Artisan::call('tenants:migrate');
$new_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName(); $new_connection_name = app(\Illuminate\Database\DatabaseManager::class)->connection()->getName();
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
$this->assertEquals($old_connection_name, $new_connection_name); expect($new_connection_name)->toEqual($old_connection_name);
$this->assertNotEquals('tenant', $new_connection_name); $this->assertNotEquals('tenant', $new_connection_name);
} });
/** @test */ test('migrate command works without options', function () {
public function migrate_command_works_without_options()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate'); Artisan::call('tenants:migrate');
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertTrue(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeTrue();
} });
/** @test */ test('migrate command works with tenants option', function () {
public function migrate_command_works_with_tenants_option()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
Artisan::call('tenants:migrate', [ Artisan::call('tenants:migrate', [
'--tenants' => [$tenant['id']], '--tenants' => [$tenant['id']],
]); ]);
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize(Tenant::create()); tenancy()->initialize(Tenant::create());
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertTrue(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeTrue();
} });
/** @test */ test('migrate command loads schema state', function () {
public function migrate_command_loads_schema_state()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$this->assertFalse(Schema::hasTable('schema_users')); expect(Schema::hasTable('schema_users'))->toBeFalse();
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate --schema-path="tests/Etc/tenant-schema.dump"'); Artisan::call('tenants:migrate --schema-path="tests/Etc/tenant-schema.dump"');
$this->assertFalse(Schema::hasTable('schema_users')); expect(Schema::hasTable('schema_users'))->toBeFalse();
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
// Check for both tables to see if missing migrations also get executed // Check for both tables to see if missing migrations also get executed
$this->assertTrue(Schema::hasTable('schema_users')); expect(Schema::hasTable('schema_users'))->toBeTrue();
$this->assertTrue(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeTrue();
} });
/** @test */ test('dump command works', function () {
public function dump_command_works()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
Artisan::call('tenants:migrate'); Artisan::call('tenants:migrate');
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
Artisan::call('tenants:dump --path="tests/Etc/tenant-schema-test.dump"'); Artisan::call('tenants:dump --path="tests/Etc/tenant-schema-test.dump"');
$this->assertFileExists('tests/Etc/tenant-schema-test.dump'); expect('tests/Etc/tenant-schema-test.dump')->toBeFile();
} });
/** @test */ test('rollback command works', function () {
public function rollback_command_works()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
Artisan::call('tenants:migrate'); Artisan::call('tenants:migrate');
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertTrue(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeTrue();
Artisan::call('tenants:rollback'); Artisan::call('tenants:rollback');
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
} });
/** @test */ // Incomplete test
public function seed_command_works() test('seed command works');
{
$this->markTestIncomplete();
}
/** @test */ test('database connection is switched to default', function () {
public function database_connection_is_switched_to_default() databaseConnectionSwitchedToDefault();
{ });
$originalDBName = DB::connection()->getDatabaseName();
Artisan::call('tenants:migrate'); test('database connection is switched to default when tenancy has been initialized', function () {
$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()); tenancy()->initialize(Tenant::create());
$this->database_connection_is_switched_to_default(); databaseConnectionSwitchedToDefault();
} });
/** @test */ test('run command works', function () {
public function run_commands_works() runCommandWorks();
{ });
$id = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate', ['--tenants' => [$id]]); test('install command works', function () {
$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'))) { if (! is_dir($dir = app_path('Http'))) {
mkdir($dir, 0777, true); mkdir($dir, 0777, true);
} }
@ -193,39 +141,35 @@ class CommandsTest extends TestCase
} }
$this->artisan('tenancy:install'); $this->artisan('tenancy:install');
$this->assertFileExists(base_path('routes/tenant.php')); expect(base_path('routes/tenant.php'))->toBeFile();
$this->assertFileExists(base_path('config/tenancy.php')); expect(base_path('config/tenancy.php'))->toBeFile();
$this->assertFileExists(app_path('Providers/TenancyServiceProvider.php')); expect(app_path('Providers/TenancyServiceProvider.php'))->toBeFile();
$this->assertFileExists(database_path('migrations/2019_09_15_000010_create_tenants_table.php')); expect(database_path('migrations/2019_09_15_000010_create_tenants_table.php'))->toBeFile();
$this->assertFileExists(database_path('migrations/2019_09_15_000020_create_domains_table.php')); expect(database_path('migrations/2019_09_15_000020_create_domains_table.php'))->toBeFile();
$this->assertDirectoryExists(database_path('migrations/tenant')); expect(database_path('migrations/tenant'))->toBeDirectory();
} });
/** @test */ test('migrate fresh command works', function () {
public function migrate_fresh_command_works()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
Artisan::call('tenants:migrate-fresh'); Artisan::call('tenants:migrate-fresh');
$this->assertFalse(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeFalse();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertTrue(Schema::hasTable('users')); expect(Schema::hasTable('users'))->toBeTrue();
$this->assertFalse(DB::table('users')->exists()); expect(DB::table('users')->exists())->toBeFalse();
DB::table('users')->insert(['name' => 'xxx', 'password' => bcrypt('password'), 'email' => 'foo@bar.xxx']); DB::table('users')->insert(['name' => 'xxx', 'password' => bcrypt('password'), 'email' => 'foo@bar.xxx']);
$this->assertTrue(DB::table('users')->exists()); expect(DB::table('users')->exists())->toBeTrue();
// test that db is wiped // test that db is wiped
Artisan::call('tenants:migrate-fresh'); Artisan::call('tenants:migrate-fresh');
$this->assertFalse(DB::table('users')->exists()); expect(DB::table('users')->exists())->toBeFalse();
} });
/** @test */ test('run command with array of tenants works', function () {
public function run_command_with_array_of_tenants_works()
{
$tenantId1 = Tenant::create()->getTenantKey(); $tenantId1 = Tenant::create()->getTenantKey();
$tenantId2 = Tenant::create()->getTenantKey(); $tenantId2 = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate-fresh'); Artisan::call('tenants:migrate-fresh');
@ -233,5 +177,36 @@ class CommandsTest extends TestCase
$this->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'") $this->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
->expectsOutput('Tenant: ' . $tenantId1) ->expectsOutput('Tenant: ' . $tenantId1)
->expectsOutput('Tenant: ' . $tenantId2); ->expectsOutput('Tenant: ' . $tenantId2);
});
// todo@tests
function runCommandWorks(): void
{
$id = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
test()->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');
} }
// todo@tests
function databaseConnectionSwitchedToDefault()
{
$originalDBName = DB::connection()->getDatabaseName();
Artisan::call('tenants:migrate');
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
Artisan::call('tenants:seed', ['--class' => ExampleSeeder::class]);
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
Artisan::call('tenants:rollback');
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
runCommandWorks();
expect(DB::connection()->getDatabaseName())->toBe($originalDBName);
} }

View file

@ -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,12 +11,10 @@ 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 () {
{
/** @test */
public function database_can_be_created_after_tenant_creation()
{
config(['tenancy.database.template_tenant_connection' => 'mysql']); 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) {
@ -33,12 +26,10 @@ class DatabasePreparationTest extends TestCase
$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([ Event::listen(TenantCreated::class, JobPipeline::make([
CreateDatabase::class, CreateDatabase::class,
MigrateDatabase::class, MigrateDatabase::class,
@ -49,13 +40,11 @@ class DatabasePreparationTest extends TestCase
$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' => [ config(['tenancy.seeder_parameters' => [
'--class' => TestSeeder::class, '--class' => TestSeeder::class,
]]); ]]);
@ -71,13 +60,11 @@ class DatabasePreparationTest extends TestCase
$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' => [ config(['tenancy.seeder_parameters' => [
'--class' => TestSeeder::class, '--class' => TestSeeder::class,
]]); ]]);
@ -94,33 +81,15 @@ class DatabasePreparationTest extends TestCase
$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;

View file

@ -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,12 +18,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
config([ config([
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class, 'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
'tenancy.database.suffix' => '', 'tenancy.database.suffix' => '',
@ -35,11 +28,9 @@ class DatabaseUsersTest extends TestCase
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());
} });
/** @test */ test('users are created when permission controlled mysql manager is used', function () {
public function users_are_created_when_permission_controlled_mysql_manager_is_used()
{
$tenant = new Tenant([ $tenant = new Tenant([
'id' => 'foo' . Str::random(10), 'id' => 'foo' . Str::random(10),
]); ]);
@ -47,16 +38,14 @@ class DatabaseUsersTest extends TestCase
/** @var ManagesDatabaseUsers $manager */ /** @var ManagesDatabaseUsers $manager */
$manager = $tenant->database()->manager(); $manager = $tenant->database()->manager();
$this->assertFalse($manager->userExists($tenant->database()->getUsername())); expect($manager->userExists($tenant->database()->getUsername()))->toBeFalse();
$tenant->save(); $tenant->save();
$this->assertTrue($manager->userExists($tenant->database()->getUsername())); expect($manager->userExists($tenant->database()->getUsername()))->toBeTrue();
} });
/** @test */ test('a tenants database cannot be created when the user already exists', function () {
public function a_tenants_database_cannot_be_created_when_the_user_already_exists()
{
$username = 'foo' . Str::random(8); $username = 'foo' . Str::random(8);
$tenant = Tenant::create([ $tenant = Tenant::create([
'tenancy_db_username' => $username, 'tenancy_db_username' => $username,
@ -64,8 +53,8 @@ class DatabaseUsersTest extends TestCase
/** @var ManagesDatabaseUsers $manager */ /** @var ManagesDatabaseUsers $manager */
$manager = $tenant->database()->manager(); $manager = $tenant->database()->manager();
$this->assertTrue($manager->userExists($tenant->database()->getUsername())); expect($manager->userExists($tenant->database()->getUsername()))->toBeTrue();
$this->assertTrue($manager->databaseExists($tenant->database()->getName())); expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
$this->expectException(TenantDatabaseUserAlreadyExistsException::class); $this->expectException(TenantDatabaseUserAlreadyExistsException::class);
Event::fake([DatabaseCreated::class]); Event::fake([DatabaseCreated::class]);
@ -78,13 +67,11 @@ class DatabaseUsersTest extends TestCase
$manager2 = $tenant2->database()->manager(); $manager2 = $tenant2->database()->manager();
// database was not created because of DB transaction // database was not created because of DB transaction
$this->assertFalse($manager2->databaseExists($tenant2->database()->getName())); expect($manager2->databaseExists($tenant2->database()->getName()))->toBeFalse();
Event::assertNotDispatched(DatabaseCreated::class); Event::assertNotDispatched(DatabaseCreated::class);
} });
/** @test */ test('correct grants are given to users', function () {
public function correct_grants_are_given_to_users()
{
PermissionControlledMySQLDatabaseManager::$grants = [ PermissionControlledMySQLDatabaseManager::$grants = [
'ALTER', 'ALTER ROUTINE', 'CREATE', 'ALTER', 'ALTER ROUTINE', 'CREATE',
]; ];
@ -94,12 +81,10 @@ class DatabaseUsersTest extends TestCase
]); ]);
$query = DB::connection('mysql')->select("SHOW GRANTS FOR `{$tenant->database()->getUsername()}`@`%`")[1]; $query = DB::connection('mysql')->select("SHOW GRANTS FOR `{$tenant->database()->getUsername()}`@`%`")[1];
$this->assertStringStartsWith('GRANT CREATE, ALTER, ALTER ROUTINE ON', $query->{"Grants for {$user}@%"}); // @mysql because that's the hostname within the docker network expect($query->{"Grants for {$user}@%"})->toStartWith('GRANT CREATE, ALTER, ALTER ROUTINE ON'); // @mysql because that's the hostname within the docker network
} });
/** @test */ test('having existing databases without users and switching to permission controlled mysql manager doesnt break existing dbs', function () {
public function having_existing_databases_without_users_and_switching_to_permission_controlled_mysql_manager_doesnt_break_existing_dbs()
{
config([ config([
'tenancy.database.managers.mysql' => MySQLDatabaseManager::class, 'tenancy.database.managers.mysql' => MySQLDatabaseManager::class,
'tenancy.database.suffix' => '', 'tenancy.database.suffix' => '',
@ -115,7 +100,7 @@ class DatabaseUsersTest extends TestCase
'id' => 'foo' . Str::random(10), 'id' => 'foo' . Str::random(10),
]); ]);
$this->assertTrue($tenant->database()->manager() instanceof MySQLDatabaseManager); expect($tenant->database()->manager() instanceof MySQLDatabaseManager)->toBeTrue();
tenancy()->initialize($tenant); // check if everything works tenancy()->initialize($tenant); // check if everything works
tenancy()->end(); tenancy()->end();
@ -124,7 +109,6 @@ class DatabaseUsersTest extends TestCase
tenancy()->initialize($tenant); // check if everything works tenancy()->initialize($tenant); // check if everything works
$this->assertTrue($tenant->database()->manager() instanceof PermissionControlledMySQLDatabaseManager); expect($tenant->database()->manager() instanceof PermissionControlledMySQLDatabaseManager)->toBeTrue();
$this->assertSame('root', config('database.connections.tenant.username')); expect(config('database.connections.tenant.username'))->toBe('root');
} });
}

View file

@ -2,23 +2,14 @@
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 () {
{
public function setUp(): void
{
parent::setUp();
config(['tenancy.tenant_model' => DatabaseAndDomainTenant::class]); config(['tenancy.tenant_model' => DatabaseAndDomainTenant::class]);
} });
/** @test */ test('job delete domains successfully', function (){
public function job_delete_domains_successfully()
{
$tenant = DatabaseAndDomainTenant::create(); $tenant = DatabaseAndDomainTenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
@ -28,15 +19,14 @@ class DeleteDomainsJobTest extends TestCase
'domain' => 'bar.localhost', 'domain' => 'bar.localhost',
]); ]);
$this->assertSame($tenant->domains()->count(), 2); expect($tenant->domains()->count())->toBe(2);
(new DeleteDomains($tenant))->handle(); (new DeleteDomains($tenant))->handle();
$this->assertSame($tenant->refresh()->domains()->count(), 0); expect($tenant->refresh()->domains()->count())->toBe(0);
} });
}
class DatabaseAndDomainTenant extends Etc\Tenant class DatabaseAndDomainTenant extends \Stancl\Tenancy\Tests\Etc\Tenant
{ {
use HasDomains; use HasDomains;
} }

View file

@ -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,12 +11,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
Route::group([ Route::group([
'middleware' => InitializeTenancyByDomain::class, 'middleware' => InitializeTenancyByDomain::class,
], function () { ], function () {
@ -28,11 +21,9 @@ class DomainTest extends TestCase
}); });
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;
@ -43,13 +34,11 @@ class DomainTest extends TestCase
$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([
@ -62,19 +51,15 @@ class DomainTest extends TestCase
$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([ $tenant = DomainTenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
@ -83,19 +68,17 @@ class DomainTest extends TestCase
'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 () { InitializeTenancyByDomain::$onFail = function () {
return 'foo'; return 'foo';
}; };
@ -103,20 +86,17 @@ class DomainTest extends TestCase
$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
View 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'),
]);
}
}

View file

@ -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,11 +20,7 @@ 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 () {
{
/** @test */
public function listeners_can_be_synchronous()
{
Queue::fake(); Queue::fake();
Event::listen(TenantCreated::class, FooListener::class); Event::listen(TenantCreated::class, FooListener::class);
@ -34,12 +28,10 @@ class EventListenerTest extends TestCase
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);
@ -51,23 +43,19 @@ class EventListenerTest extends TestCase
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 () { Event::listen(CreatingTenant::class, function () {
return false; 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 () {
@ -82,12 +70,10 @@ class EventListenerTest extends TestCase
'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::listen(CreatingDatabase::class, function (CreatingDatabase $event) {
$event->tenant->setInternal('create_database', false); $event->tenant->setInternal('create_database', false);
}); });
@ -98,11 +84,9 @@ class EventListenerTest extends TestCase
$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' => [ config(['tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class, DatabaseTenancyBootstrapper::class,
RedisTenancyBootstrapper::class, RedisTenancyBootstrapper::class,
@ -125,12 +109,10 @@ class EventListenerTest extends TestCase
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(
@ -173,11 +155,9 @@ class EventListenerTest extends TestCase
'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( Event::listen(
TenantCreated::class, TenantCreated::class,
JobPipeline::make([ JobPipeline::make([
@ -196,9 +176,8 @@ class EventListenerTest extends TestCase
'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
{ {

View file

@ -2,18 +2,11 @@
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 () {
{
/** @test */
public function tenant_redirect_macro_replaces_only_the_hostname()
{
config([ config([
'tenancy.features' => [CrossDomainRedirect::class], 'tenancy.features' => [CrossDomainRedirect::class],
]); ]);
@ -31,16 +24,13 @@ class RedirectTest extends TestCase
$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 () { Route::get('/abcdef/{a?}/{b?}', function () {
return 'Foo'; return 'Foo';
})->name('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');
} });
}

View file

@ -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,21 +9,13 @@ 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 () {
{
public function tearDown(): void
{
TenantConfig::$storageToConfigMap = []; TenantConfig::$storageToConfigMap = [];
});
parent::tearDown(); test('config is merged and removed', function () {
} expect(config('services.paypal'))->toBe(null);
/** @test */
public function config_is_merged_and_removed()
{
$this->assertSame(null, config('services.paypal'));
config([ config([
'tenancy.features' => [TenantConfig::class], 'tenancy.features' => [TenantConfig::class],
'tenancy.bootstrappers' => [], 'tenancy.bootstrappers' => [],
@ -44,19 +34,17 @@ class TenantConfigTest extends TestCase
]); ]);
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame(['public' => 'foo', 'private' => 'bar'], config('services.paypal')); expect(config('services.paypal'))->toBe(['public' => 'foo', 'private' => 'bar']);
tenancy()->end(); tenancy()->end();
$this->assertSame([ $this->assertSame([
'public' => null, 'public' => null,
'private' => null, 'private' => null,
], config('services.paypal')); ], config('services.paypal'));
} });
/** @test */ test('the value can be set to multiple config keys', function () {
public function the_value_can_be_set_to_multiple_config_keys() expect(config('services.paypal'))->toBe(null);
{
$this->assertSame(null, config('services.paypal'));
config([ config([
'tenancy.features' => [TenantConfig::class], 'tenancy.features' => [TenantConfig::class],
'tenancy.bootstrappers' => [], 'tenancy.bootstrappers' => [],
@ -90,5 +78,4 @@ class TenantConfigTest extends TestCase
'public2' => null, 'public2' => null,
'private' => null, 'private' => null,
], config('services.paypal')); ], config('services.paypal'));
} });
}

View file

@ -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 () {
{
public function setUp(): void
{
parent::setUp();
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
CacheTenancyBootstrapper::class, CacheTenancyBootstrapper::class,
]]); ]]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
} });
/** @test */ test('global cache manager stores data in global cache', function () {
public function global_cache_manager_stores_data_in_global_cache() expect(cache('foo'))->toBe(null);
{
$this->assertSame(null, cache('foo'));
GlobalCache::put(['foo' => 'bar'], 1); GlobalCache::put(['foo' => 'bar'], 1);
$this->assertSame('bar', GlobalCache::get('foo')); expect(GlobalCache::get('foo'))->toBe('bar');
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('bar', GlobalCache::get('foo')); expect(GlobalCache::get('foo'))->toBe('bar');
GlobalCache::put(['abc' => 'xyz'], 1); GlobalCache::put(['abc' => 'xyz'], 1);
cache(['def' => 'ghi'], 10); cache(['def' => 'ghi'], 10);
$this->assertSame('ghi', cache('def')); expect(cache('def'))->toBe('ghi');
tenancy()->end(); tenancy()->end();
$this->assertSame('xyz', GlobalCache::get('abc')); expect(GlobalCache::get('abc'))->toBe('xyz');
$this->assertSame('bar', GlobalCache::get('foo')); expect(GlobalCache::get('foo'))->toBe('bar');
$this->assertSame(null, cache('def')); expect(cache('def'))->toBe(null);
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertSame('xyz', GlobalCache::get('abc')); expect(GlobalCache::get('abc'))->toBe('xyz');
$this->assertSame('bar', GlobalCache::get('foo')); expect(GlobalCache::get('foo'))->toBe('bar');
$this->assertSame(null, cache('def')); expect(cache('def'))->toBe(null);
cache(['def' => 'xxx'], 1); cache(['def' => 'xxx'], 1);
$this->assertSame('xxx', cache('def')); expect(cache('def'))->toBe('xxx');
tenancy()->initialize($tenant1); tenancy()->initialize($tenant1);
$this->assertSame('ghi', cache('def')); expect(cache('def'))->toBe('ghi');
} });
}

View file

@ -2,20 +2,14 @@
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 () {
{
/** @test */
public function tenant_can_be_in_maintenance_mode()
{
Route::get('/foo', function () { Route::get('/foo', function () {
return 'bar'; return 'bar';
})->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]); })->middleware([InitializeTenancyByDomain::class, CheckTenantForMaintenanceMode::class]);
@ -35,8 +29,7 @@ class MaintenanceModeTest extends TestCase
$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
{ {

View file

@ -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,12 +9,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
PathTenantResolver::$tenantParameterName = 'tenant'; PathTenantResolver::$tenantParameterName = 'tenant';
Route::group([ Route::group([
@ -27,63 +20,52 @@ class PathIdentificationTest extends TestCase
return "$a + $b"; return "$a + $b";
}); });
}); });
} });
public function tearDown(): void
{
parent::tearDown();
afterEach(function () {
// Global state cleanup // Global state cleanup
PathTenantResolver::$tenantParameterName = 'tenant'; PathTenantResolver::$tenantParameterName = 'tenant';
} });
/** @test */ test('tenant can be identified by path', function () {
public function tenant_can_be_identified_by_path()
{
Tenant::create([ Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
$this->assertFalse(tenancy()->initialized); expect(tenancy()->initialized)->toBeFalse();
$this->get('/acme/foo/abc/xyz'); $this->get('/acme/foo/abc/xyz');
$this->assertTrue(tenancy()->initialized); expect(tenancy()->initialized)->toBeTrue();
$this->assertSame('acme', tenant('id')); expect(tenant('id'))->toBe('acme');
} });
/** @test */ test('route actions dont get the tenant id', function () {
public function route_actions_dont_get_the_tenant_id()
{
Tenant::create([ Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
$this->assertFalse(tenancy()->initialized); expect(tenancy()->initialized)->toBeFalse();
$this $this
->get('/acme/foo/abc/xyz') ->get('/acme/foo/abc/xyz')
->assertContent('abc + xyz'); ->assertContent('abc + xyz');
$this->assertTrue(tenancy()->initialized); expect(tenancy()->initialized)->toBeTrue();
$this->assertSame('acme', tenant('id')); expect(tenant('id'))->toBe('acme');
} });
/** @test */ test('exception is thrown when tenant cannot be identified by path', function () {
public function exception_is_thrown_when_tenant_cannot_be_identified_by_path()
{
$this->expectException(TenantCouldNotBeIdentifiedByPathException::class); $this->expectException(TenantCouldNotBeIdentifiedByPathException::class);
$this $this
->withoutExceptionHandling() ->withoutExceptionHandling()
->get('/acme/foo/abc/xyz'); ->get('/acme/foo/abc/xyz');
$this->assertFalse(tenancy()->initialized); expect(tenancy()->initialized)->toBeFalse();
} });
/** @test */ test('onfail logic can be customized', function () {
public function onfail_logic_can_be_customized()
{
InitializeTenancyByPath::$onFail = function () { InitializeTenancyByPath::$onFail = function () {
return 'foo'; return 'foo';
}; };
@ -91,11 +73,9 @@ class PathIdentificationTest extends TestCase
$this $this
->get('/acme/foo/abc/xyz') ->get('/acme/foo/abc/xyz')
->assertContent('foo'); ->assertContent('foo');
} });
/** @test */ test('an exception is thrown when the routes first parameter is not tenant', function () {
public function an_exception_is_thrown_when_the_routes_first_parameter_is_not_tenant()
{
Route::group([ Route::group([
// 'prefix' => '/{tenant}', -- intentionally commented // 'prefix' => '/{tenant}', -- intentionally commented
'middleware' => InitializeTenancyByPath::class, 'middleware' => InitializeTenancyByPath::class,
@ -114,11 +94,9 @@ class PathIdentificationTest extends TestCase
$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([
@ -144,5 +122,4 @@ class PathIdentificationTest extends TestCase
$this $this
->withoutExceptionHandling() ->withoutExceptionHandling()
->get('/acme/foo/abc/xyz'); ->get('/acme/foo/abc/xyz');
} });
}

3
tests/Pest.php Normal file
View file

@ -0,0 +1,3 @@
<?php
uses(Stancl\Tenancy\Tests\TestCase::class)->in(__DIR__);

View file

@ -2,45 +2,32 @@
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
{
public $mockConsoleOutput = false;
/** @var Valuestore */
protected $valuestore;
public function setUp(): void
{
parent::setUp();
beforeEach(function () {
config([ config([
'tenancy.bootstrappers' => [ 'tenancy.bootstrappers' => [
QueueTenancyBootstrapper::class, QueueTenancyBootstrapper::class,
@ -52,65 +39,14 @@ class QueueTest extends TestCase
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
$this->createValueStore(); createValueStore();
} });
public function tearDown(): void afterEach(function () {
{
$this->valuestore->flush(); $this->valuestore->flush();
}
protected function createValueStore(): void
{
$valueStorePath = __DIR__ . '/Etc/tmp/queuetest.json';
if (! file_exists($valueStorePath)) {
// The directory sometimes goes missing as well when the file is deleted in git
if (! is_dir(__DIR__ . '/Etc/tmp')) {
mkdir(__DIR__ . '/Etc/tmp');
}
file_put_contents($valueStorePath, '');
}
$this->valuestore = Valuestore::make($valueStorePath)->flush();
}
protected function withFailedJobs()
{
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
}); });
}
protected function withUsers() test('tenant id is passed to tenant queues', function () {
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
protected function withTenantDatabases()
{
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());
}
/** @test */
public function tenant_id_is_passed_to_tenant_queues()
{
config(['queue.default' => 'sync']); config(['queue.default' => 'sync']);
$tenant = Tenant::create(); $tenant = Tenant::create();
@ -124,11 +60,9 @@ class QueueTest extends TestCase
Event::assertDispatched(JobProcessing::class, function ($event) { Event::assertDispatched(JobProcessing::class, function ($event) {
return $event->job->payload()['tenant_id'] === tenant('id'); return $event->job->payload()['tenant_id'] === tenant('id');
}); });
} });
/** @test */ test('tenant id is not passed to central queues', function () {
public function tenant_id_is_not_passed_to_central_queues()
{
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
@ -145,24 +79,17 @@ class QueueTest extends TestCase
Event::assertDispatched(JobProcessing::class, function ($event) { Event::assertDispatched(JobProcessing::class, function ($event) {
return ! isset($event->job->payload()['tenant_id']); return ! isset($event->job->payload()['tenant_id']);
}); });
} });
/** test('tenancy is initialized inside queues', function (bool $shouldEndTenancy) {
* @test withTenantDatabases();
* withFailedJobs();
* @testWith [true]
* [false]
*/
public function tenancy_is_initialized_inside_queues(bool $shouldEndTenancy)
{
$this->withTenantDatabases();
$this->withFailedJobs();
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->withUsers(); withUsers();
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']); $user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
@ -170,7 +97,7 @@ class QueueTest extends TestCase
dispatch(new TestJob($this->valuestore, $user)); dispatch(new TestJob($this->valuestore, $user));
$this->assertFalse($this->valuestore->has('tenant_id')); expect($this->valuestore->has('tenant_id'))->toBeFalse();
if ($shouldEndTenancy) { if ($shouldEndTenancy) {
tenancy()->end(); tenancy()->end();
@ -178,35 +105,28 @@ class QueueTest extends TestCase
$this->artisan('queue:work --once'); $this->artisan('queue:work --once');
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count()); expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id')); expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id);
$tenant->run(function () use ($user) { $tenant->run(function () use ($user) {
$this->assertSame('Bar', $user->fresh()->name); expect($user->fresh()->name)->toBe('Bar');
}); });
} })->with([true, false]);;
/** test('tenancy is initialized when retrying jobs', function (bool $shouldEndTenancy) {
* @test
*
* @testWith [true]
* [false]
*/
public function tenancy_is_initialized_when_retrying_jobs(bool $shouldEndTenancy)
{
if (! Str::startsWith(app()->version(), '8')) { if (! Str::startsWith(app()->version(), '8')) {
$this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8'); $this->markTestSkipped('queue:retry tenancy is only supported in Laravel 8');
} }
$this->withFailedJobs(); withFailedJobs();
$this->withTenantDatabases(); withTenantDatabases();
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->withUsers(); withUsers();
$user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']); $user = User::create(['name' => 'Foo', 'email' => 'foo@bar.com', 'password' => 'secret']);
@ -215,7 +135,7 @@ class QueueTest extends TestCase
dispatch(new TestJob($this->valuestore, $user)); dispatch(new TestJob($this->valuestore, $user));
$this->assertFalse($this->valuestore->has('tenant_id')); expect($this->valuestore->has('tenant_id'))->toBeFalse();
if ($shouldEndTenancy) { if ($shouldEndTenancy) {
tenancy()->end(); tenancy()->end();
@ -223,24 +143,22 @@ class QueueTest extends TestCase
$this->artisan('queue:work --once'); $this->artisan('queue:work --once');
$this->assertSame(1, DB::connection('central')->table('failed_jobs')->count()); expect(DB::connection('central')->table('failed_jobs')->count())->toBe(1);
$this->assertNull($this->valuestore->get('tenant_id')); // job failed expect($this->valuestore->get('tenant_id'))->toBeNull(); // job failed
$this->artisan('queue:retry all'); $this->artisan('queue:retry all');
$this->artisan('queue:work --once'); $this->artisan('queue:work --once');
$this->assertSame(0, DB::connection('central')->table('failed_jobs')->count()); expect(DB::connection('central')->table('failed_jobs')->count())->toBe(0);
$this->assertSame('The current tenant id is: ' . $tenant->id, $this->valuestore->get('tenant_id')); // job succeeded expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: ' . $tenant->id); // job succeeded
$tenant->run(function () use ($user) { $tenant->run(function () use ($user) {
$this->assertSame('Bar', $user->fresh()->name); expect($user->fresh()->name)->toBe('Bar');
}); });
} })->with([true, false]);
/** @test */ test('the tenant used by the job doesnt change when the current tenant changes', function () {
public function the_tenant_used_by_the_job_doesnt_change_when_the_current_tenant_changes()
{
$tenant1 = Tenant::create([ $tenant1 = Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
@ -255,11 +173,58 @@ class QueueTest extends TestCase
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertFalse($this->valuestore->has('tenant_id')); expect($this->valuestore->has('tenant_id'))->toBeFalse();
$this->artisan('queue:work --once'); $this->artisan('queue:work --once');
$this->assertSame('The current tenant id is: acme', $this->valuestore->get('tenant_id')); expect($this->valuestore->get('tenant_id'))->toBe('The current tenant id is: acme');
});
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, '');
}
test()->valuestore = Valuestore::make($valueStorePath)->flush();
}
function withFailedJobs()
{
Schema::connection('central')->create('failed_jobs', function (Blueprint $table) {
$table->increments('id');
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
function withUsers()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
function withTenantDatabases()
{
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant;
})->toListener());
} }
class TestJob implements ShouldQueue class TestJob implements ShouldQueue
@ -297,3 +262,4 @@ class TestJob implements ShouldQueue
} }
} }
} }

View file

@ -2,18 +2,11 @@
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 () {
{
public function setUp(): void
{
parent::setUp();
config([ config([
'tenancy.central_domains' => [ 'tenancy.central_domains' => [
'localhost', 'localhost',
@ -23,19 +16,14 @@ class RequestDataIdentificationTest extends TestCase
Route::middleware(InitializeTenancyByRequestData::class)->get('/test', function () { Route::middleware(InitializeTenancyByRequestData::class)->get('/test', function () {
return 'Tenant id: ' . tenant('id'); return 'Tenant id: ' . tenant('id');
}); });
} });
public function tearDown(): void afterEach(function () {
{
InitializeTenancyByRequestData::$header = 'X-Tenant'; InitializeTenancyByRequestData::$header = 'X-Tenant';
InitializeTenancyByRequestData::$queryParameter = 'tenant'; InitializeTenancyByRequestData::$queryParameter = 'tenant';
});
parent::tearDown(); test('header identification works', function () {
}
/** @test */
public function header_identification_works()
{
InitializeTenancyByRequestData::$header = 'X-Tenant'; InitializeTenancyByRequestData::$header = 'X-Tenant';
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
@ -46,11 +34,9 @@ class RequestDataIdentificationTest extends TestCase
'X-Tenant' => $tenant->id, 'X-Tenant' => $tenant->id,
]) ])
->assertSee($tenant->id); ->assertSee($tenant->id);
} });
/** @test */ test('query parameter identification works', function () {
public function query_parameter_identification_works()
{
InitializeTenancyByRequestData::$header = null; InitializeTenancyByRequestData::$header = null;
InitializeTenancyByRequestData::$queryParameter = 'tenant'; InitializeTenancyByRequestData::$queryParameter = 'tenant';
@ -61,5 +47,4 @@ class RequestDataIdentificationTest extends TestCase
->withoutExceptionHandling() ->withoutExceptionHandling()
->get('test?tenant=' . $tenant->id) ->get('test?tenant=' . $tenant->id)
->assertSee($tenant->id); ->assertSee($tenant->id);
} });
}

View file

@ -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\Eloquent\Relations\BelongsToMany; use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Events\CallQueuedListener; use Illuminate\Events\CallQueuedListener;
@ -30,12 +28,7 @@ use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Listeners\UpdateSyncedResource; use Stancl\Tenancy\Listeners\UpdateSyncedResource;
use Stancl\Tenancy\Tests\Etc\Tenant; use Stancl\Tenancy\Tests\Etc\Tenant;
class ResourceSyncingTest extends TestCase beforeEach(function () {
{
public function setUp(): void
{
parent::setUp();
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class, DatabaseTenancyBootstrapper::class,
]]); ]]);
@ -54,26 +47,16 @@ class ResourceSyncingTest extends TestCase
UpdateSyncedResource::$shouldQueue = false; // global state cleanup UpdateSyncedResource::$shouldQueue = false; // global state cleanup
Event::listen(SyncedResourceSaved::class, UpdateSyncedResource::class); Event::listen(SyncedResourceSaved::class, UpdateSyncedResource::class);
$this->artisan('migrate', [ test()->artisan('migrate', [
'--path' => [ '--path' => [
__DIR__ . '/Etc/synced_resource_migrations', __DIR__ . '/Etc/synced_resource_migrations',
__DIR__ . '/Etc/synced_resource_migrations/users', __DIR__ . '/Etc/synced_resource_migrations/users',
], ],
'--realpath' => true, '--realpath' => true,
])->assertExitCode(0); ])->assertExitCode(0);
} });
protected function migrateTenants() test('an event is triggered when a synced resource is changed', function () {
{
$this->artisan('tenants:migrate', [
'--path' => __DIR__ . '/Etc/synced_resource_migrations/users',
'--realpath' => true,
])->assertExitCode(0);
}
/** @test */
public function an_event_is_triggered_when_a_synced_resource_is_changed()
{
Event::fake([SyncedResourceSaved::class]); Event::fake([SyncedResourceSaved::class]);
$user = ResourceUser::create([ $user = ResourceUser::create([
@ -87,11 +70,9 @@ class ResourceSyncingTest extends TestCase
Event::assertDispatched(SyncedResourceSaved::class, function (SyncedResourceSaved $event) use ($user) { Event::assertDispatched(SyncedResourceSaved::class, function (SyncedResourceSaved $event) use ($user) {
return $event->model === $user; return $event->model === $user;
}); });
} });
/** @test */ test('only the synced columns are updated in the central db', function () {
public function only_the_synced_columns_are_updated_in_the_central_db()
{
// Create user in central DB // Create user in central DB
$user = CentralUser::create([ $user = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
@ -102,7 +83,7 @@ class ResourceSyncingTest extends TestCase
]); ]);
$tenant = ResourceTenant::create(); $tenant = ResourceTenant::create();
$this->migrateTenants(); migrateTenantsResource();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
@ -143,58 +124,23 @@ class ResourceSyncingTest extends TestCase
'password' => 'secret', // no changes 'password' => 'secret', // no changes
'role' => 'superadmin', // unsynced 'role' => 'superadmin', // unsynced
], ResourceUser::first()->getAttributes()); ], ResourceUser::first()->getAttributes());
} });
/** @test */ test('creating the resource in tenant database creates it in central database and creates the mapping', function () {
public function creating_the_resource_in_tenant_database_creates_it_in_central_database_and_creates_the_mapping() creatingResourceInTenantDatabaseCreatesAndMapInCentralDatabase();
{ });
// Assert no user in central DB
$this->assertCount(0, ResourceUser::all());
$tenant = ResourceTenant::create(); test('trying to update synced resources from central context using tenant models results in an exception', function () {
$this->migrateTenants(); creatingResourceInTenantDatabaseCreatesAndMapInCentralDatabase();
tenancy()->initialize($tenant);
// Create the same user in tenant DB
ResourceUser::create([
'global_id' => 'acme',
'name' => 'John Doe',
'email' => 'john@localhost',
'password' => 'secret',
'role' => 'commenter', // unsynced
]);
tenancy()->end(); tenancy()->end();
expect(tenancy()->initialized)->toBeFalse();
// Asset user was created
$this->assertSame('acme', CentralUser::first()->global_id);
$this->assertSame('commenter', CentralUser::first()->role);
// Assert mapping was created
$this->assertCount(1, CentralUser::first()->tenants);
// Assert role change doesn't cascade
CentralUser::first()->update(['role' => 'central superadmin']);
tenancy()->initialize($tenant);
$this->assertSame('commenter', ResourceUser::first()->role);
}
/** @test */
public function trying_to_update_synced_resources_from_central_context_using_tenant_models_results_in_an_exception()
{
$this->creating_the_resource_in_tenant_database_creates_it_in_central_database_and_creates_the_mapping();
tenancy()->end();
$this->assertFalse(tenancy()->initialized);
$this->expectException(ModelNotSyncMasterException::class); $this->expectException(ModelNotSyncMasterException::class);
ResourceUser::first()->update(['role' => 'foobar']); ResourceUser::first()->update(['role' => 'foobar']);
} });
/** @test */ test('attaching a tenant to the central resource triggers a pull from the tenant db', function () {
public function attaching_a_tenant_to_the_central_resource_triggers_a_pull_from_the_tenant_db()
{
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
'name' => 'John Doe', 'name' => 'John Doe',
@ -206,22 +152,20 @@ class ResourceSyncingTest extends TestCase
$tenant = ResourceTenant::create([ $tenant = ResourceTenant::create([
'id' => 't1', 'id' => 't1',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
$tenant->run(function () { $tenant->run(function () {
$this->assertCount(0, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(0);
}); });
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
$tenant->run(function () { $tenant->run(function () {
$this->assertCount(1, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(1);
});
}); });
}
/** @test */ test('attaching users to tenants does not do anything', function () {
public function attaching_users_to_tenants_DOES_NOT_DO_ANYTHING()
{
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
'name' => 'John Doe', 'name' => 'John Doe',
@ -233,10 +177,10 @@ class ResourceSyncingTest extends TestCase
$tenant = ResourceTenant::create([ $tenant = ResourceTenant::create([
'id' => 't1', 'id' => 't1',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
$tenant->run(function () { $tenant->run(function () {
$this->assertCount(0, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(0);
}); });
// The child model is inaccessible in the Pivot Model, so we can't fire any events. // The child model is inaccessible in the Pivot Model, so we can't fire any events.
@ -244,13 +188,11 @@ class ResourceSyncingTest extends TestCase
$tenant->run(function () { $tenant->run(function () {
// Still zero // Still zero
$this->assertCount(0, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(0);
});
}); });
}
/** @test */ test('resources are synced only to workspaces that have the resource', function () {
public function resources_are_synced_only_to_workspaces_that_have_the_resource()
{
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
'name' => 'John Doe', 'name' => 'John Doe',
@ -270,7 +212,7 @@ class ResourceSyncingTest extends TestCase
$t3 = ResourceTenant::create([ $t3 = ResourceTenant::create([
'id' => 't3', 'id' => 't3',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
$centralUser->tenants()->attach('t2'); $centralUser->tenants()->attach('t2');
@ -278,23 +220,21 @@ class ResourceSyncingTest extends TestCase
$t1->run(function () { $t1->run(function () {
// assert user exists // assert user exists
$this->assertCount(1, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(1);
}); });
$t2->run(function () { $t2->run(function () {
// assert user exists // assert user exists
$this->assertCount(1, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(1);
}); });
$t3->run(function () { $t3->run(function () {
// assert user does NOT exist // assert user does NOT exist
$this->assertCount(0, ResourceUser::all()); expect(ResourceUser::all())->toHaveCount(0);
});
}); });
}
/** @test */ test('when a resource exists in other tenant dbs but is created in a tenant db the synced columns are updated in the other dbs', function () {
public function when_a_resource_exists_in_other_tenant_dbs_but_is_CREATED_in_a_tenant_db_the_synced_columns_are_updated_in_the_other_dbs()
{
// create shared resource // create shared resource
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
@ -310,7 +250,7 @@ class ResourceSyncingTest extends TestCase
$t2 = ResourceTenant::create([ $t2 = ResourceTenant::create([
'id' => 't2', 'id' => 't2',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
// Copy (cascade) user to t1 DB // Copy (cascade) user to t1 DB
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
@ -327,21 +267,19 @@ class ResourceSyncingTest extends TestCase
}); });
$centralUser = CentralUser::first(); $centralUser = CentralUser::first();
$this->assertSame('John Foo', $centralUser->name); // name changed expect($centralUser->name)->toBe('John Foo'); // name changed
$this->assertSame('john@foo', $centralUser->email); // email changed expect($centralUser->email)->toBe('john@foo'); // email changed
$this->assertSame('commenter', $centralUser->role); // role didn't change expect($centralUser->role)->toBe('commenter'); // role didn't change
$t1->run(function () { $t1->run(function () {
$user = ResourceUser::first(); $user = ResourceUser::first();
$this->assertSame('John Foo', $user->name); // name changed expect($user->name)->toBe('John Foo'); // name changed
$this->assertSame('john@foo', $user->email); // email changed expect($user->email)->toBe('john@foo'); // email changed
$this->assertSame('commenter', $user->role); // role didn't change, i.e. is the same as from the original copy from central expect($user->role)->toBe('commenter'); // role didn't change, i.e. is the same as from the original copy from central
});
}); });
}
/** @test */ test('the synced columns are updated in other tenant dbs where the resource exists', function () {
public function the_synced_columns_are_updated_in_other_tenant_dbs_where_the_resource_exists()
{
// create shared resource // create shared resource
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'global_id' => 'acme', 'global_id' => 'acme',
@ -360,7 +298,7 @@ class ResourceSyncingTest extends TestCase
$t3 = ResourceTenant::create([ $t3 = ResourceTenant::create([
'id' => 't3', 'id' => 't3',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
// Copy (cascade) user to t1 DB // Copy (cascade) user to t1 DB
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
@ -373,28 +311,26 @@ class ResourceSyncingTest extends TestCase
'role' => 'employee', // unsynced 'role' => 'employee', // unsynced
]); ]);
$this->assertSame('employee', ResourceUser::first()->role); expect(ResourceUser::first()->role)->toBe('employee');
}); });
// Check that change was cascaded to other tenants // Check that change was cascaded to other tenants
$t1->run($check = function () { $t1->run($check = function () {
$user = ResourceUser::first(); $user = ResourceUser::first();
$this->assertSame('John 3', $user->name); // synced expect($user->name)->toBe('John 3'); // synced
$this->assertSame('commenter', $user->role); // unsynced expect($user->role)->toBe('commenter'); // unsynced
}); });
$t2->run($check); $t2->run($check);
// Check that change bubbled up to central DB // Check that change bubbled up to central DB
$this->assertSame(1, CentralUser::count()); expect(CentralUser::count())->toBe(1);
$centralUser = CentralUser::first(); $centralUser = CentralUser::first();
$this->assertSame('John 3', $centralUser->name); // synced expect($centralUser->name)->toBe('John 3'); // synced
$this->assertSame('commenter', $centralUser->role); // unsynced expect($centralUser->role)->toBe('commenter'); // unsynced
} });
/** @test */ test('global id is generated using id generator when its not supplied', function () {
public function global_id_is_generated_using_id_generator_when_its_not_supplied()
{
$user = CentralUser::create([ $user = CentralUser::create([
'name' => 'John Doe', 'name' => 'John Doe',
'email' => 'john@doe', 'email' => 'john@doe',
@ -403,11 +339,9 @@ class ResourceSyncingTest extends TestCase
]); ]);
$this->assertNotNull($user->global_id); $this->assertNotNull($user->global_id);
} });
/** @test */ test('when the resource doesnt exist in the tenant db non synced columns will cascade too', function () {
public function when_the_resource_doesnt_exist_in_the_tenant_db_non_synced_columns_will_cascade_too()
{
$centralUser = CentralUser::create([ $centralUser = CentralUser::create([
'name' => 'John Doe', 'name' => 'John Doe',
'email' => 'john@doe', 'email' => 'john@doe',
@ -419,23 +353,21 @@ class ResourceSyncingTest extends TestCase
'id' => 't1', 'id' => 't1',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
$t1->run(function () { $t1->run(function () {
$this->assertSame('employee', ResourceUser::first()->role); expect(ResourceUser::first()->role)->toBe('employee');
});
}); });
}
/** @test */ test('when the resource doesnt exist in the central db non synced columns will bubble up too', function () {
public function when_the_resource_doesnt_exist_in_the_central_db_non_synced_columns_will_bubble_up_too()
{
$t1 = ResourceTenant::create([ $t1 = ResourceTenant::create([
'id' => 't1', 'id' => 't1',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
$t1->run(function () { $t1->run(function () {
ResourceUser::create([ ResourceUser::create([
@ -446,12 +378,10 @@ class ResourceSyncingTest extends TestCase
]); ]);
}); });
$this->assertSame('employee', CentralUser::first()->role); expect(CentralUser::first()->role)->toBe('employee');
} });
/** @test */ test('the listener can be queued', function () {
public function the_listener_can_be_queued()
{
Queue::fake(); Queue::fake();
UpdateSyncedResource::$shouldQueue = true; UpdateSyncedResource::$shouldQueue = true;
@ -459,7 +389,7 @@ class ResourceSyncingTest extends TestCase
'id' => 't1', 'id' => 't1',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
Queue::assertNothingPushed(); Queue::assertNothingPushed();
@ -475,11 +405,9 @@ class ResourceSyncingTest extends TestCase
Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) { Queue::assertPushed(CallQueuedListener::class, function (CallQueuedListener $job) {
return $job->class === UpdateSyncedResource::class; return $job->class === UpdateSyncedResource::class;
}); });
} });
/** @test */ test('an event is fired for all touched resources', function () {
public function an_event_is_fired_for_all_touched_resources()
{
Event::fake([SyncedResourceChangedInForeignDatabase::class]); Event::fake([SyncedResourceChangedInForeignDatabase::class]);
// create shared resource // create shared resource
@ -500,7 +428,7 @@ class ResourceSyncingTest extends TestCase
$t3 = ResourceTenant::create([ $t3 = ResourceTenant::create([
'id' => 't3', 'id' => 't3',
]); ]);
$this->migrateTenants(); migrateTenantsResource();
// Copy (cascade) user to t1 DB // Copy (cascade) user to t1 DB
$centralUser->tenants()->attach('t1'); $centralUser->tenants()->attach('t1');
@ -532,7 +460,7 @@ class ResourceSyncingTest extends TestCase
'role' => 'employee', // unsynced 'role' => 'employee', // unsynced
]); ]);
$this->assertSame('employee', ResourceUser::first()->role); expect(ResourceUser::first()->role)->toBe('employee');
}); });
Event::assertDispatched(SyncedResourceChangedInForeignDatabase::class, function (SyncedResourceChangedInForeignDatabase $event) { Event::assertDispatched(SyncedResourceChangedInForeignDatabase::class, function (SyncedResourceChangedInForeignDatabase $event) {
@ -572,7 +500,49 @@ class ResourceSyncingTest extends TestCase
Event::assertNotDispatched(SyncedResourceChangedInForeignDatabase::class, function (SyncedResourceChangedInForeignDatabase $event) { Event::assertNotDispatched(SyncedResourceChangedInForeignDatabase::class, function (SyncedResourceChangedInForeignDatabase $event) {
return $event->tenant === null; return $event->tenant === null;
}); });
});
// todo@tests
function creatingResourceInTenantDatabaseCreatesAndMapInCentralDatabase()
{
// Assert no user in central DB
expect(ResourceUser::all())->toHaveCount(0);
$tenant = ResourceTenant::create();
migrateTenantsResource();
tenancy()->initialize($tenant);
// Create the same user in tenant DB
ResourceUser::create([
'global_id' => 'acme',
'name' => 'John Doe',
'email' => 'john@localhost',
'password' => 'secret',
'role' => 'commenter', // unsynced
]);
tenancy()->end();
// Asset user was created
expect(CentralUser::first()->global_id)->toBe('acme');
expect(CentralUser::first()->role)->toBe('commenter');
// Assert mapping was created
expect(CentralUser::first()->tenants)->toHaveCount(1);
// Assert role change doesn't cascade
CentralUser::first()->update(['role' => 'central superadmin']);
tenancy()->initialize($tenant);
expect(ResourceUser::first()->role)->toBe('commenter');
} }
function migrateTenantsResource()
{
test()->artisan('tenants:migrate', [
'--path' => __DIR__ . '/Etc/synced_resource_migrations/users',
'--realpath' => true,
])->assertExitCode(0);
} }
class ResourceTenant extends Tenant class ResourceTenant extends Tenant

View file

@ -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,12 +11,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
Route::group([ Route::group([
'middleware' => [StartSession::class, InitializeTenancyBySubdomain::class, ScopeSessions::class], 'middleware' => [StartSession::class, InitializeTenancyBySubdomain::class, ScopeSessions::class],
], function () { ], function () {
@ -35,22 +28,18 @@ class ScopeSessionsTest extends TestCase
'domain' => $tenant->id, 'domain' => $tenant->id,
]); ]);
}); });
} });
/** @test */ test('tenant id is auto added to session if its missing', function () {
public function tenant_id_is_auto_added_to_session_if_its_missing()
{
$tenant = Tenant::create([ $tenant = Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
$this->get('http://acme.localhost/foo') $this->get('http://acme.localhost/foo')
->assertSessionHas(ScopeSessions::$tenantIdKey, 'acme'); ->assertSessionHas(ScopeSessions::$tenantIdKey, 'acme');
} });
/** @test */ test('changing tenant id in session will abort the request', function () {
public function changing_tenant_id_in_session_will_abort_the_request()
{
$tenant = Tenant::create([ $tenant = Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
@ -62,11 +51,9 @@ class ScopeSessionsTest extends TestCase
$this->get('http://acme.localhost/foo') $this->get('http://acme.localhost/foo')
->assertStatus(403); ->assertStatus(403);
} });
/** @test */ test('an exception is thrown when the middleware is executed before tenancy is initialized', function () {
public function an_exception_is_thrown_when_the_middleware_is_executed_before_tenancy_is_initialized()
{
Route::get('/bar', function () { Route::get('/bar', function () {
return true; return true;
})->middleware([StartSession::class, ScopeSessions::class]); })->middleware([StartSession::class, ScopeSessions::class]);
@ -77,5 +64,4 @@ class ScopeSessionsTest extends TestCase
$this->expectException(TenancyNotInitializedException::class); $this->expectException(TenancyNotInitializedException::class);
$this->withoutExceptionHandling()->get('http://acme.localhost/bar'); $this->withoutExceptionHandling()->get('http://acme.localhost/bar');
} });
}

View file

@ -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,12 +12,7 @@ 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 () {
{
public function setUp(): void
{
parent::setUp();
BelongsToTenant::$tenantIdColumn = 'tenant_id'; BelongsToTenant::$tenantIdColumn = 'tenant_id';
Schema::create('posts', function (Blueprint $table) { Schema::create('posts', function (Blueprint $table) {
@ -41,106 +34,34 @@ class SingleDatabaseTenancyTest extends TestCase
}); });
config(['tenancy.tenant_model' => Tenant::class]); config(['tenancy.tenant_model' => Tenant::class]);
} });
/** @test */ test('primary models are scoped to the current tenant', function () {
public function primary_models_are_scoped_to_the_current_tenant() primaryModelsScopedToCurrentTenant();
{ });
// acme context
tenancy()->initialize($acme = Tenant::create([
'id' => 'acme',
]));
$post = Post::create(['text' => 'Foo']); test('primary models are not scoped in the central context', function () {
primaryModelsScopedToCurrentTenant();
$this->assertSame('acme', $post->tenant_id);
$this->assertSame('acme', $post->tenant->id);
$post = Post::first();
$this->assertSame('acme', $post->tenant_id);
$this->assertSame('acme', $post->tenant->id);
// ======================================
// foobar context
tenancy()->initialize($foobar = Tenant::create([
'id' => 'foobar',
]));
$post = Post::create(['text' => 'Bar']);
$this->assertSame('foobar', $post->tenant_id);
$this->assertSame('foobar', $post->tenant->id);
$post = Post::first();
$this->assertSame('foobar', $post->tenant_id);
$this->assertSame('foobar', $post->tenant->id);
// ======================================
// acme context again
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(); tenancy()->end();
$this->assertSame(2, Post::count()); expect(Post::count())->toBe(2);
} });
/** @test */ test('secondary models are scoped to the current tenant when accessed via primary model', function () {
public function secondary_models_are_scoped_to_the_current_tenant_when_accessed_via_primary_model() secondaryModelsAreScopedToCurrentTenant();
{ });
// acme context
tenancy()->initialize($acme = Tenant::create([
'id' => 'acme',
]));
$post = Post::create(['text' => 'Foo']); test('secondary models are not scoped to the current tenant when accessed directly', function () {
$post->comments()->create(['text' => 'Comment text']); secondaryModelsAreScopedToCurrentTenant();
// ================
// 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 // We're in acme context
$this->assertSame('acme', tenant('id')); expect(tenant('id'))->toBe('acme');
$this->assertSame(2, Comment::count()); expect(Comment::count())->toBe(2);
} });
/** @test */ test('secondary models a r e scoped to the current tenant when accessed directly and parent relationship traitis used', function () {
public function secondary_models_ARE_scoped_to_the_current_tenant_when_accessed_directly_AND_PARENT_RELATIONSHIP_TRAIT_IS_USED()
{
$acme = Tenant::create([ $acme = Tenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
@ -149,8 +70,8 @@ class SingleDatabaseTenancyTest extends TestCase
$post = Post::create(['text' => 'Foo']); $post = Post::create(['text' => 'Foo']);
$post->scoped_comments()->create(['text' => 'Comment Text']); $post->scoped_comments()->create(['text' => 'Comment Text']);
$this->assertSame(1, Post::count()); expect(Post::count())->toBe(1);
$this->assertSame(1, ScopedComment::count()); expect(ScopedComment::count())->toBe(1);
}); });
$foobar = Tenant::create([ $foobar = Tenant::create([
@ -158,33 +79,29 @@ class SingleDatabaseTenancyTest extends TestCase
]); ]);
$foobar->run(function () { $foobar->run(function () {
$this->assertSame(0, Post::count()); expect(Post::count())->toBe(0);
$this->assertSame(0, ScopedComment::count()); expect(ScopedComment::count())->toBe(0);
$post = Post::create(['text' => 'Bar']); $post = Post::create(['text' => 'Bar']);
$post->scoped_comments()->create(['text' => 'Comment Text 2']); $post->scoped_comments()->create(['text' => 'Comment Text 2']);
$this->assertSame(1, Post::count()); expect(Post::count())->toBe(1);
$this->assertSame(1, ScopedComment::count()); expect(ScopedComment::count())->toBe(1);
}); });
// Global context // Global context
$this->assertSame(2, ScopedComment::count()); expect(ScopedComment::count())->toBe(2);
} });
/** @test */ test('secondary models are not scoped in the central context', function () {
public function secondary_models_are_NOT_scoped_in_the_central_context() secondaryModelsAreScopedToCurrentTenant();
{
$this->secondary_models_are_scoped_to_the_current_tenant_when_accessed_via_primary_model();
tenancy()->end(); tenancy()->end();
$this->assertSame(2, Comment::count()); expect(Comment::count())->toBe(2);
} });
/** @test */ test('global models are not scoped at all', function () {
public function global_models_are_not_scoped_at_all()
{
Schema::create('global_resources', function (Blueprint $table) { Schema::create('global_resources', function (Blueprint $table) {
$table->increments('id'); $table->increments('id');
$table->string('text'); $table->string('text');
@ -198,41 +115,35 @@ class SingleDatabaseTenancyTest extends TestCase
]); ]);
$acme->run(function () { $acme->run(function () {
$this->assertSame(2, GlobalResource::count()); expect(GlobalResource::count())->toBe(2);
GlobalResource::create(['text' => 'Third']); GlobalResource::create(['text' => 'Third']);
GlobalResource::create(['text' => 'Fourth']); GlobalResource::create(['text' => 'Fourth']);
}); });
$this->assertSame(4, GlobalResource::count()); expect(GlobalResource::count())->toBe(4);
} });
/** @test */ test('tenant id and relationship is auto added when creating primary resources in tenant context', function () {
public function tenant_id_and_relationship_is_auto_added_when_creating_primary_resources_in_tenant_context()
{
tenancy()->initialize($acme = Tenant::create([ tenancy()->initialize($acme = Tenant::create([
'id' => 'acme', 'id' => 'acme',
])); ]));
$post = Post::create(['text' => 'Foo']); $post = Post::create(['text' => 'Foo']);
$this->assertSame('acme', $post->tenant_id); expect($post->tenant_id)->toBe('acme');
$this->assertTrue($post->relationLoaded('tenant')); expect($post->relationLoaded('tenant'))->toBeTrue();
$this->assertSame($acme, $post->tenant); expect($post->tenant)->toBe($acme);
$this->assertSame(tenant(), $post->tenant); expect($post->tenant)->toBe(tenant());
} });
/** @test */ test('tenant id is not auto added when creating primary resources in central context', function () {
public function tenant_id_is_not_auto_added_when_creating_primary_resources_in_central_context()
{
$this->expectException(QueryException::class); $this->expectException(QueryException::class);
Post::create(['text' => 'Foo']); Post::create(['text' => 'Foo']);
} });
/** @test */ test('tenant id column name can be customized', function () {
public function tenant_id_column_name_can_be_customized()
{
BelongsToTenant::$tenantIdColumn = 'team_id'; BelongsToTenant::$tenantIdColumn = 'team_id';
Schema::drop('comments'); Schema::drop('comments');
@ -252,7 +163,7 @@ class SingleDatabaseTenancyTest extends TestCase
$post = Post::create(['text' => 'Foo']); $post = Post::create(['text' => 'Foo']);
$this->assertSame('acme', $post->team_id); expect($post->team_id)->toBe('acme');
// ====================================== // ======================================
// foobar context // foobar context
@ -262,11 +173,11 @@ class SingleDatabaseTenancyTest extends TestCase
$post = Post::create(['text' => 'Bar']); $post = Post::create(['text' => 'Bar']);
$this->assertSame('foobar', $post->team_id); expect($post->team_id)->toBe('foobar');
$post = Post::first(); $post = Post::first();
$this->assertSame('foobar', $post->team_id); expect($post->team_id)->toBe('foobar');
// ====================================== // ======================================
// acme context again // acme context again
@ -274,15 +185,13 @@ class SingleDatabaseTenancyTest extends TestCase
tenancy()->initialize($acme); tenancy()->initialize($acme);
$post = Post::first(); $post = Post::first();
$this->assertSame('acme', $post->team_id); expect($post->team_id)->toBe('acme');
// Assert foobar models are inaccessible in acme context // Assert foobar models are inaccessible in acme context
$this->assertSame(1, Post::count()); expect(Post::count())->toBe(1);
} });
/** @test */ test('the model returned by the tenant helper has unique and exists validation rules', function () {
public function the_model_returned_by_the_tenant_helper_has_unique_and_exists_validation_rules()
{
Schema::table('posts', function (Blueprint $table) { Schema::table('posts', function (Blueprint $table) {
$table->string('slug')->nullable(); $table->string('slug')->nullable();
$table->unique(['tenant_id', 'slug']); $table->unique(['tenant_id', 'slug']);
@ -314,9 +223,82 @@ class SingleDatabaseTenancyTest extends TestCase
])->fails(); ])->fails();
// Assert that tenant()->unique() and tenant()->exists() are scoped // Assert that tenant()->unique() and tenant()->exists() are scoped
$this->assertTrue($uniqueFails); expect($uniqueFails)->toBeTrue();
$this->assertFalse($existsFails); expect($existsFails)->toBeFalse();
});
// todo@tests
function primaryModelsScopedToCurrentTenant()
{
// acme context
tenancy()->initialize($acme = Tenant::create([
'id' => 'acme',
]));
$post = Post::create(['text' => 'Foo']);
expect($post->tenant_id)->toBe('acme');
expect($post->tenant->id)->toBe('acme');
$post = Post::first();
expect($post->tenant_id)->toBe('acme');
expect($post->tenant->id)->toBe('acme');
// ======================================
// foobar context
tenancy()->initialize($foobar = Tenant::create([
'id' => 'foobar',
]));
$post = Post::create(['text' => 'Bar']);
expect($post->tenant_id)->toBe('foobar');
expect($post->tenant->id)->toBe('foobar');
$post = Post::first();
expect($post->tenant_id)->toBe('foobar');
expect($post->tenant->id)->toBe('foobar');
// ======================================
// acme context again
tenancy()->initialize($acme);
$post = Post::first();
expect($post->tenant_id)->toBe('acme');
expect($post->tenant->id)->toBe('acme');
// Assert foobar models are inaccessible in acme context
expect(Post::count())->toBe(1);
} }
// todo@tests
function secondaryModelsAreScopedToCurrentTenant()
{
// 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);
expect(Post::count())->toBe(1);
expect(Post::first()->comments->count())->toBe(1);
} }
class Tenant extends TestTenant class Tenant extends TestTenant

View file

@ -2,20 +2,13 @@
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 () {
{
public function setUp(): void
{
parent::setUp();
// Global state cleanup after some tests // Global state cleanup after some tests
InitializeTenancyBySubdomain::$onFail = null; InitializeTenancyBySubdomain::$onFail = null;
@ -28,11 +21,9 @@ class SubdomainTest extends TestCase
}); });
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([ $tenant = SubdomainTenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
@ -41,19 +32,17 @@ class SubdomainTest extends TestCase
'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 () { InitializeTenancyBySubdomain::$onFail = function () {
return 'foo'; return 'foo';
}; };
@ -61,31 +50,25 @@ class SubdomainTest extends TestCase
$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 // in this case, we need to return a response instance
// since a string would be treated as the subdomain // since a string would be treated as the subdomain
InitializeTenancyBySubdomain::$onFail = function ($e) { InitializeTenancyBySubdomain::$onFail = function ($e) {
@ -100,11 +83,9 @@ class SubdomainTest extends TestCase
->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' => [ config(['tenancy.central_domains' => [
'127.0.0.1', '127.0.0.1',
// not 'localhost' // not 'localhost'
@ -123,11 +104,9 @@ class SubdomainTest extends TestCase
$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' => [ config(['tenancy.central_domains' => [
'localhost', 'localhost',
]]); ]]);
@ -145,8 +124,7 @@ class SubdomainTest extends TestCase
$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
{ {

View file

@ -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,43 +13,20 @@ 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 () {
{
public function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app->booted(function () {
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' => [ config(['tenancy.bootstrappers' => [
FilesystemTenancyBootstrapper::class, FilesystemTenancyBootstrapper::class,
]]); ]]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class); Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
} });
public function tearDown(): void
{
parent::tearDown();
afterEach(function () {
// Cleanup // Cleanup
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByDomain::class; TenantAssetsController::$tenancyMiddleware = InitializeTenancyByDomain::class;
} });
/** @test */ test('asset can be accessed using the url returned by the tenant asset helper', function () {
public function asset_can_be_accessed_using_the_url_returned_by_the_tenant_asset_helper()
{
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByRequestData::class; TenantAssetsController::$tenancyMiddleware = InitializeTenancyByRequestData::class;
$tenant = Tenant::create(); $tenant = Tenant::create();
@ -63,7 +38,7 @@ class TenantAssetTest extends TestCase
// response()->file() returns BinaryFileResponse whose content is // response()->file() returns BinaryFileResponse whose content is
// inaccessible via getContent, so ->assertSee() can't be used // inaccessible via getContent, so ->assertSee() can't be used
$this->assertFileExists($path); expect($path)->toBeFile();
$response = $this->get(tenant_asset($filename), [ $response = $this->get(tenant_asset($filename), [
'X-Tenant' => $tenant->id, 'X-Tenant' => $tenant->id,
]); ]);
@ -74,46 +49,38 @@ class TenantAssetTest extends TestCase
$content = fread($f, filesize($path)); $content = fread($f, filesize($path));
fclose($f); fclose($f);
$this->assertSame('bar', $content); expect($content)->toBe('bar');
} });
/** @test */ test('asset helper returns a link to tenant asset controller when asset url is null', function () {
public function asset_helper_returns_a_link_to_TenantAssetController_when_asset_url_is_null()
{
config(['app.asset_url' => null]); config(['app.asset_url' => null]);
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame(route('stancl.tenancy.asset', ['path' => 'foo']), asset('foo')); expect(asset('foo'))->toBe(route('stancl.tenancy.asset', ['path' => 'foo']));
} });
/** @test */ test('asset helper returns a link to an external url when asset url is not null', function () {
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']); config(['app.asset_url' => 'https://an-s3-bucket']);
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame("https://an-s3-bucket/tenant{$tenant->id}/foo", asset('foo')); expect(asset('foo'))->toBe("https://an-s3-bucket/tenant{$tenant->id}/foo");
} });
/** @test */ test('global asset helper returns the same url regardless of tenancy initialization', function () {
public function global_asset_helper_returns_the_same_url_regardless_of_tenancy_initialization()
{
$original = global_asset('foobar'); $original = global_asset('foobar');
$this->assertSame(asset('foobar'), global_asset('foobar')); expect(global_asset('foobar'))->toBe(asset('foobar'));
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame($original, global_asset('foobar')); expect(global_asset('foobar'))->toBe($original);
} });
/** @test */ test('asset helper tenancy can be disabled', function () {
public function asset_helper_tenancy_can_be_disabled()
{
$original = asset('foo'); $original = asset('foo');
config([ config([
@ -124,6 +91,16 @@ class TenantAssetTest extends TestCase
$tenant = Tenant::create(); $tenant = Tenant::create();
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertSame($original, asset('foo')); expect(asset('foo'))->toBe($original);
});
function getEnvironmentSetUp($app)
{
$app->booted(function () {
if (file_exists(base_path('routes/tenant.php'))) {
Route::middleware(['web'])
->namespace(test()->app['config']['tenancy.tenant_route_namespace'] ?? 'App\Http\Controllers')
->group(base_path('routes/tenant.php'));
} }
});
} }

View file

@ -2,17 +2,11 @@
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 () {
{
/** @test */
public function commands_run_globally_are_tenant_aware_and_return_valid_exit_code()
{
$tenant1 = Tenant::create(); $tenant1 = Tenant::create();
$tenant2 = Tenant::create(); $tenant2 = Tenant::create();
Artisan::call('tenants:migrate', [ Artisan::call('tenants:migrate', [
@ -29,5 +23,4 @@ class TenantAwareCommandTest extends TestCase
tenancy()->initialize($tenant2); tenancy()->initialize($tenant2);
$this->assertNotEmpty(DB::table('users')->get()); $this->assertNotEmpty(DB::table('users')->get());
tenancy()->end(); tenancy()->end();
} });
}

View file

@ -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,14 +24,7 @@ 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) {
{
/**
* @test
* @dataProvider database_manager_provider
*/
public function databases_can_be_created_and_deleted($driver, $databaseManager)
{
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());
@ -48,22 +38,20 @@ class TenantDatabaseManagerTest extends TestCase
$manager = app($databaseManager); $manager = app($databaseManager);
$manager->setConnection($driver); $manager->setConnection($driver);
$this->assertFalse($manager->databaseExists($name)); expect($manager->databaseExists($name))->toBeFalse();
$tenant = Tenant::create([ $tenant = Tenant::create([
'tenancy_db_name' => $name, 'tenancy_db_name' => $name,
'tenancy_db_connection' => $driver, 'tenancy_db_connection' => $driver,
]); ]);
$this->assertTrue($manager->databaseExists($name)); expect($manager->databaseExists($name))->toBeTrue();
$manager->deleteDatabase($tenant); $manager->deleteDatabase($tenant);
$this->assertFalse($manager->databaseExists($name)); expect($manager->databaseExists($name))->toBeFalse();
} })->with('database_manager_provider');
/** @test */ test('dbs can be created when another driver is used for the central db', function () {
public function dbs_can_be_created_when_another_driver_is_used_for_the_central_db() expect(config('database.default'))->toBe('central');
{
$this->assertSame('central', config('database.default'));
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;
@ -74,43 +62,29 @@ class TenantDatabaseManagerTest extends TestCase
$mysqlmanager = app(MySQLDatabaseManager::class); $mysqlmanager = app(MySQLDatabaseManager::class);
$mysqlmanager->setConnection('mysql'); $mysqlmanager->setConnection('mysql');
$this->assertFalse($mysqlmanager->databaseExists($database)); expect($mysqlmanager->databaseExists($database))->toBeFalse();
Tenant::create([ Tenant::create([
'tenancy_db_name' => $database, 'tenancy_db_name' => $database,
'tenancy_db_connection' => 'mysql', 'tenancy_db_connection' => 'mysql',
]); ]);
$this->assertTrue($mysqlmanager->databaseExists($database)); expect($mysqlmanager->databaseExists($database))->toBeTrue();
$postgresManager = app(PostgreSQLDatabaseManager::class); $postgresManager = app(PostgreSQLDatabaseManager::class);
$postgresManager->setConnection('pgsql'); $postgresManager->setConnection('pgsql');
$database = 'db' . $this->randomString(); $database = 'db' . $this->randomString();
$this->assertFalse($postgresManager->databaseExists($database)); expect($postgresManager->databaseExists($database))->toBeFalse();
Tenant::create([ Tenant::create([
'tenancy_db_name' => $database, 'tenancy_db_name' => $database,
'tenancy_db_connection' => 'pgsql', 'tenancy_db_connection' => 'pgsql',
]); ]);
$this->assertTrue($postgresManager->databaseExists($database)); expect($postgresManager->databaseExists($database))->toBeTrue();
} });
public function database_manager_provider() test('the tenant connection is fully removed', function () {
{
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([ config([
'tenancy.boostrappers' => [ 'tenancy.boostrappers' => [
DatabaseTenancyBootstrapper::class, DatabaseTenancyBootstrapper::class,
@ -126,37 +100,23 @@ class TenantDatabaseManagerTest extends TestCase
$tenant = Tenant::create(); $tenant = Tenant::create();
$this->assertSame(['central'], array_keys(app('db')->getConnections())); expect(array_keys(app('db')->getConnections()))->toBe(['central']);
$this->assertArrayNotHasKey('tenant', config('database.connections')); $this->assertArrayNotHasKey('tenant', config('database.connections'));
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->createUsersTable(); createUsersTable();
$this->assertSame(['central', 'tenant'], array_keys(app('db')->getConnections())); expect(array_keys(app('db')->getConnections()))->toBe(['central', 'tenant']);
$this->assertArrayHasKey('tenant', config('database.connections')); $this->assertArrayHasKey('tenant', config('database.connections'));
tenancy()->end(); tenancy()->end();
$this->assertSame(['central'], array_keys(app('db')->getConnections())); expect(array_keys(app('db')->getConnections()))->toBe(['central']);
$this->assertNull(config('database.connections.tenant')); expect(config('database.connections.tenant'))->toBeNull();
}
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 */ test('db name is prefixed with db path when sqlite is used', function () {
public function db_name_is_prefixed_with_db_path_when_sqlite_is_used()
{
if (file_exists(database_path('foodb'))) { if (file_exists(database_path('foodb'))) {
unlink(database_path('foodb')); // cleanup unlink(database_path('foodb')); // cleanup
} }
@ -170,12 +130,10 @@ class TenantDatabaseManagerTest extends TestCase
]); ]);
app(DatabaseManager::class)->createTenantConnection($tenant); app(DatabaseManager::class)->createTenantConnection($tenant);
$this->assertSame(config('database.connections.tenant.database'), database_path('foodb')); expect(database_path('foodb'))->toBe(config('database.connections.tenant.database'));
} });
/** @test */ test('schema manager uses schema to separate tenant dbs', function () {
public function schema_manager_uses_schema_to_separate_tenant_dbs()
{
config([ config([
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class, 'tenancy.database.managers.pgsql' => \Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
'tenancy.boostrappers' => [ 'tenancy.boostrappers' => [
@ -200,13 +158,11 @@ class TenantDatabaseManagerTest extends TestCase
config('database.connections.' . config('database.default') . '.search_path') : config('database.connections.' . config('database.default') . '.search_path') :
config('database.connections.' . config('database.default') . '.schema'); config('database.connections.' . config('database.default') . '.schema');
$this->assertSame($tenant->database()->getName(), $schemaConfig); expect($schemaConfig)->toBe($tenant->database()->getName());
$this->assertSame($originalDatabaseName, config(['database.connections.pgsql.database'])); expect(config(['database.connections.pgsql.database']))->toBe($originalDatabaseName);
} });
/** @test */ test('a tenants database cannot be created when the database already exists', function () {
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) { Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
return $event->tenant; return $event->tenant;
})->toListener()); })->toListener());
@ -217,17 +173,15 @@ class TenantDatabaseManagerTest extends TestCase
]); ]);
$manager = $tenant->database()->manager(); $manager = $tenant->database()->manager();
$this->assertTrue($manager->databaseExists($tenant->database()->getName())); expect($manager->databaseExists($tenant->database()->getName()))->toBeTrue();
$this->expectException(TenantDatabaseAlreadyExistsException::class); $this->expectException(TenantDatabaseAlreadyExistsException::class);
$tenant2 = Tenant::create([ $tenant2 = Tenant::create([
'tenancy_db_name' => $name, 'tenancy_db_name' => $name,
]); ]);
} });
/** @test */ test('tenant database can be created on a foreign server', function () {
public function tenant_database_can_be_created_on_a_foreign_server()
{
config([ config([
'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class, 'tenancy.database.managers.mysql' => PermissionControlledMySQLDatabaseManager::class,
'database.connections.mysql2' => [ 'database.connections.mysql2' => [
@ -264,15 +218,34 @@ class TenantDatabaseManagerTest extends TestCase
$manager = $tenant->database()->manager(); $manager = $tenant->database()->manager();
$manager->setConnection('mysql'); $manager->setConnection('mysql');
$this->assertFalse($manager->databaseExists($name)); expect($manager->databaseExists($name))->toBeFalse();
$manager->setConnection('mysql2'); $manager->setConnection('mysql2');
$this->assertTrue($manager->databaseExists($name)); expect($manager->databaseExists($name))->toBeTrue();
} });
/** @test */ test('path used by sqlite manager can be customized', function () {
public function path_used_by_sqlite_manager_can_be_customized()
{
$this->markTestIncomplete(); $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) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
} }

View file

@ -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,11 +19,7 @@ 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 () {
{
/** @test */
public function created_event_is_dispatched()
{
Event::fake([TenantCreated::class]); Event::fake([TenantCreated::class]);
Event::assertNotDispatched(TenantCreated::class); Event::assertNotDispatched(TenantCreated::class);
@ -33,25 +27,21 @@ class TenantModelTest extends TestCase
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) {
@ -61,11 +51,9 @@ class TenantModelTest extends TestCase
$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::drop('domains');
Schema::table('tenants', function (Blueprint $table) { Schema::table('tenants', function (Blueprint $table) {
$table->bigIncrements('id')->change(); $table->bigIncrements('id')->change();
@ -76,35 +64,29 @@ class TenantModelTest extends TestCase
$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([ $tenant = AnotherTenant::create([
'id' => 'acme', 'id' => 'acme',
]); ]);
tenancy()->initialize($tenant); tenancy()->initialize($tenant);
$this->assertTrue(tenant() instanceof AnotherTenant); expect(tenant() instanceof AnotherTenant)->toBeTrue();
} });
/** @test */ test('tenant can be created even when we are in another tenants context', function () {
public function tenant_can_be_created_even_when_we_are_in_another_tenants_context()
{
config(['tenancy.bootstrappers' => [ config(['tenancy.bootstrappers' => [
DatabaseTenancyBootstrapper::class, DatabaseTenancyBootstrapper::class,
]]); ]]);
@ -128,22 +110,18 @@ class TenantModelTest extends TestCase
tenancy()->end(); tenancy()->end();
$this->assertSame(2, Tenant::count()); expect(Tenant::count())->toBe(2);
} });
/** @test */ test('the model uses tenant collection', function () {
public function the_model_uses_TenantCollection()
{
Tenant::create(); Tenant::create();
Tenant::create(); Tenant::create();
$this->assertSame(2, Tenant::count()); expect(Tenant::count())->toBe(2);
$this->assertTrue(Tenant::all() instanceof TenantCollection); expect(Tenant::all() instanceof TenantCollection)->toBeTrue();
} });
/** @test */ test('a command can be run on a collection of tenants', function () {
public function a_command_can_be_run_on_a_collection_of_tenants()
{
Tenant::create([ Tenant::create([
'id' => 't1', 'id' => 't1',
'foo' => 'bar', 'foo' => 'bar',
@ -159,10 +137,9 @@ class TenantModelTest extends TestCase
]); ]);
}); });
$this->assertSame('xyz', Tenant::find('t1')->foo); expect(Tenant::find('t1')->foo)->toBe('xyz');
$this->assertSame('xyz', Tenant::find('t2')->foo); expect(Tenant::find('t2')->foo)->toBe('xyz');
} });
}
class MyTenant extends Tenant class MyTenant extends Tenant
{ {

View file

@ -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,18 +22,9 @@ 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 () {
{
protected function migrateTenants()
{
$this->artisan('tenants:migrate')->assertExitCode(0);
}
public function setUp(): void
{
parent::setUp();
$this->artisan('migrate', [ $this->artisan('migrate', [
'--path' => __DIR__ . '/../assets/impersonation-migrations', '--path' => __DIR__ . '/../assets/impersonation-migrations',
'--realpath' => true, '--realpath' => true,
@ -63,42 +50,16 @@ class TenantUserImpersonationTest extends TestCase
Event::listen(TenancyEnded::class, RevertToCentralContext::class); Event::listen(TenancyEnded::class, RevertToCentralContext::class);
config(['auth.providers.users.model' => ImpersonationUser::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 */ test('tenant user can be impersonated on a tenant domain', function () {
public function tenant_user_can_be_impersonated_on_a_tenant_domain() Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
{
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'foo.localhost', 'domain' => 'foo.localhost',
]); ]);
$this->migrateTenants(); migrateTenants();
$user = $tenant->run(function () { $user = $tenant->run(function () {
return ImpersonationUser::create([ return ImpersonationUser::create([
'name' => 'Joe', 'name' => 'Joe',
@ -120,20 +81,18 @@ class TenantUserImpersonationTest extends TestCase
$this->get('http://foo.localhost/dashboard') $this->get('http://foo.localhost/dashboard')
->assertSuccessful() ->assertSuccessful()
->assertSee('You are logged in as Joe'); ->assertSee('You are logged in as Joe');
} });
/** @test */ test('tenant user can be impersonated on a tenant path', function () {
public function tenant_user_can_be_impersonated_on_a_tenant_path() makeLoginRoute();
{
$this->makeLoginRoute();
Route::middleware(InitializeTenancyByPath::class)->prefix('/{tenant}')->group($this->getRoutes(false)); Route::middleware(InitializeTenancyByPath::class)->prefix('/{tenant}')->group(getRoutes(false));
$tenant = Tenant::create([ $tenant = Tenant::create([
'id' => 'acme', 'id' => 'acme',
'tenancy_db_name' => 'db' . Str::random(16), 'tenancy_db_name' => 'db' . Str::random(16),
]); ]);
$this->migrateTenants(); migrateTenants();
$user = $tenant->run(function () { $user = $tenant->run(function () {
return ImpersonationUser::create([ return ImpersonationUser::create([
'name' => 'Joe', 'name' => 'Joe',
@ -155,18 +114,16 @@ class TenantUserImpersonationTest extends TestCase
$this->get('/acme/dashboard') $this->get('/acme/dashboard')
->assertSuccessful() ->assertSuccessful()
->assertSee('You are logged in as Joe'); ->assertSee('You are logged in as Joe');
} });
/** @test */ test('tokens have a limited ttl', function () {
public function tokens_have_a_limited_ttl() Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
{
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'foo.localhost', 'domain' => 'foo.localhost',
]); ]);
$this->migrateTenants(); migrateTenants();
$user = $tenant->run(function () { $user = $tenant->run(function () {
return ImpersonationUser::create([ return ImpersonationUser::create([
'name' => 'Joe', 'name' => 'Joe',
@ -184,18 +141,16 @@ class TenantUserImpersonationTest extends TestCase
$this->followingRedirects() $this->followingRedirects()
->get('http://foo.localhost/impersonate/' . $token->token) ->get('http://foo.localhost/impersonate/' . $token->token)
->assertStatus(403); ->assertStatus(403);
} });
/** @test */ test('tokens are deleted after use', function () {
public function tokens_are_deleted_after_use() Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes());
{
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes());
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'foo.localhost', 'domain' => 'foo.localhost',
]); ]);
$this->migrateTenants(); migrateTenants();
$user = $tenant->run(function () { $user = $tenant->run(function () {
return ImpersonationUser::create([ return ImpersonationUser::create([
'name' => 'Joe', 'name' => 'Joe',
@ -214,12 +169,10 @@ class TenantUserImpersonationTest extends TestCase
->assertSuccessful() ->assertSuccessful()
->assertSee('You are logged in as Joe'); ->assertSee('You are logged in as Joe');
$this->assertNull(ImpersonationToken::find($token->token)); expect(ImpersonationToken::find($token->token))->toBeNull();
} });
/** @test */ test('impersonation works with multiple models and guards', function () {
public function impersonation_works_with_multiple_models_and_guards()
{
config([ config([
'auth.guards.another' => [ 'auth.guards.another' => [
'driver' => 'session', 'driver' => 'session',
@ -235,13 +188,13 @@ class TenantUserImpersonationTest extends TestCase
return new SessionGuard($name, Auth::createUserProvider($config['provider']), session()); return new SessionGuard($name, Auth::createUserProvider($config['provider']), session());
}); });
Route::middleware(InitializeTenancyByDomain::class)->group($this->getRoutes(true, 'another')); Route::middleware(InitializeTenancyByDomain::class)->group(getRoutes(true, 'another'));
$tenant = Tenant::create(); $tenant = Tenant::create();
$tenant->domains()->create([ $tenant->domains()->create([
'domain' => 'foo.localhost', 'domain' => 'foo.localhost',
]); ]);
$this->migrateTenants(); migrateTenants();
$user = $tenant->run(function () { $user = $tenant->run(function () {
return AnotherImpersonationUser::create([ return AnotherImpersonationUser::create([
'name' => 'Joe', 'name' => 'Joe',
@ -265,10 +218,38 @@ class TenantUserImpersonationTest extends TestCase
->assertSee('You are logged in as Joe'); ->assertSee('You are logged in as Joe');
Tenant::first()->run(function () { Tenant::first()->run(function () {
$this->assertSame('Joe', auth()->guard('another')->user()->name); expect(auth()->guard('another')->user()->name)->toBe('Joe');
$this->assertSame(null, auth()->guard('web')->user()); expect(auth()->guard('web')->user())->toBe(null);
}); });
});
function migrateTenants()
{
test()->artisan('tenants:migrate')->assertExitCode(0);
} }
function makeLoginRoute()
{
Route::get('/login', function () {
return 'Please log in';
})->name('login');
}
function getRoutes($loginRoute = true, $authGuard = 'web'): Closure
{
return function () use ($loginRoute, $authGuard) {
if ($loginRoute) {
test()->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);
});
};
} }
class ImpersonationUser extends Authenticable class ImpersonationUser extends Authenticable

View file

@ -2,25 +2,16 @@
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 () {
{
public function tearDown(): void
{
InitializeTenancyByDomain::$onFail = null; InitializeTenancyByDomain::$onFail = null;
});
parent::tearDown(); test('a route can work in both central and tenant context', function () {
}
/** @test */
public function a_route_can_work_in_both_central_and_tenant_context()
{
Route::middlewareGroup('universal', []); Route::middlewareGroup('universal', []);
config(['tenancy.features' => [UniversalRoutes::class]]); config(['tenancy.features' => [UniversalRoutes::class]]);
@ -44,16 +35,37 @@ class UniversalRouteTest extends TestCase
$this->get('http://acme.localhost/foo') $this->get('http://acme.localhost/foo')
->assertSuccessful() ->assertSuccessful()
->assertSee('Tenancy is initialized.'); ->assertSee('Tenancy is initialized.');
} });
/** @test */ test('making one route universal doesnt make all routes universal', function () {
public function making_one_route_universal_doesnt_make_all_routes_universal()
{
Route::get('/bar', function () { Route::get('/bar', function () {
return tenant('id'); return tenant('id');
})->middleware(InitializeTenancyByDomain::class); })->middleware(InitializeTenancyByDomain::class);
$this->a_route_can_work_in_both_central_and_tenant_context(); Route::middlewareGroup('universal', []);
config(['tenancy.features' => [UniversalRoutes::class]]);
Route::get('/foo', function () {
return tenancy()->initialized
? 'Tenancy is initialized.'
: 'Tenancy is not initialized.';
})->middleware(['universal', InitializeTenancyByDomain::class]);
$this->get('http://localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is not initialized.');
$tenant = Tenant::create([
'id' => 'acme',
]);
$tenant->domains()->create([
'domain' => 'acme.localhost',
]);
$this->get('http://acme.localhost/foo')
->assertSuccessful()
->assertSee('Tenancy is initialized.');
tenancy()->end(); tenancy()->end();
$this->get('http://localhost/bar') $this->get('http://localhost/bar')
@ -62,5 +74,4 @@ class UniversalRouteTest extends TestCase
$this->get('http://acme.localhost/bar') $this->get('http://acme.localhost/bar')
->assertSuccessful() ->assertSuccessful()
->assertSee('acme'); ->assertSee('acme');
} });
}