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

Merge branch 'master' into storage-url-conflict-resolution

This commit is contained in:
lukinovec 2022-09-22 14:04:14 +02:00
commit 9206dafd28
109 changed files with 1147 additions and 754 deletions

View file

@ -16,6 +16,7 @@ use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Tests\Etc\ExampleSeeder;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Stancl\Tenancy\Tests\Etc\User;
beforeEach(function () {
Event::listen(TenantCreated::class, JobPipeline::make([CreateDatabase::class])->send(function (TenantCreated $event) {
@ -183,7 +184,7 @@ test('run command with array of tenants works', function () {
$tenantId2 = Tenant::create()->getTenantKey();
Artisan::call('tenants:migrate-fresh');
pest()->artisan("tenants:run foo --tenants=$tenantId1 --tenants=$tenantId2 --argument='a=foo' --option='b=bar' --option='c=xyz'")
pest()->artisan("tenants:run --tenants=$tenantId1 --tenants=$tenantId2 'foo foo --b=bar --c=xyz'")
->expectsOutput('Tenant: ' . $tenantId1)
->expectsOutput('Tenant: ' . $tenantId2);
});
@ -225,6 +226,29 @@ test('link command works with a specified tenant', function() {
$this->assertDirectoryDoesNotExist(public_path("public-$tenantKey"));
});
test('run command works when sub command asks questions and accepts arguments', function () {
$tenant = Tenant::create();
$id = $tenant->getTenantKey();
Artisan::call('tenants:migrate');
pest()->artisan("tenants:run --tenants=$id 'user:addwithname Abrar' ")
->expectsQuestion('What is your email?', 'email@localhost')
->expectsOutput("Tenant: $id")
->expectsOutput("User created: Abrar(email@localhost)");
// Assert we are in central context
expect(tenancy()->initialized)->toBeFalse();
// Assert user was created in tenant context
tenancy()->initialize($tenant);
$user = User::first();
// Assert user is same as provided using the command
expect($user->name)->toBe('Abrar');
expect($user->email)->toBe('email@localhost');
});
// todo@tests
function runCommandWorks(): void
{
@ -232,7 +256,7 @@ function runCommandWorks(): void
Artisan::call('tenants:migrate', ['--tenants' => [$id]]);
pest()->artisan("tenants:run foo --tenants=$id --argument='a=foo' --option='b=bar' --option='c=xyz'")
pest()->artisan("tenants:run --tenants=$id 'foo foo --b=bar --c=xyz' ")
->expectsOutput("User's name is Test command")
->expectsOutput('foo')
->expectsOutput('xyz');

View file

@ -9,7 +9,7 @@ use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Jobs\MigrateDatabase;
use Stancl\Tenancy\Jobs\SeedDatabase;
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Foundation\Auth\User as Authenticable;
use Stancl\Tenancy\Tests\Etc\TestSeeder;

View file

@ -11,11 +11,11 @@ use Stancl\Tenancy\Contracts\ManagesDatabaseUsers;
use Stancl\Tenancy\Events\DatabaseCreated;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Exceptions\TenantDatabaseUserAlreadyExistsException;
use Stancl\Tenancy\Database\Exceptions\TenantDatabaseUserAlreadyExistsException;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\Tests\Etc\Tenant;
beforeEach(function () {

68
tests/DebuggableTest.php Normal file
View file

@ -0,0 +1,68 @@
<?php
use Stancl\Tenancy\Enums\LogMode;
use Stancl\Tenancy\Events\EndingTenancy;
use Stancl\Tenancy\Events\InitializingTenancy;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Tests\Etc\Tenant;
test('tenancy can log events silently', function () {
tenancy()->log(LogMode::SILENT);
$tenant = Tenant::create();
tenancy()->initialize($tenant);
tenancy()->end();
assertTenancyInitializedAndEnded(tenancy()->getLog(), $tenant);
});
test('tenancy logs event silently by default', function () {
tenancy()->log();
expect(tenancy()->logMode())->toBe(LogMode::SILENT);
});
test('the log can be dumped', function (string $method) {
tenancy()->log();
$tenant = Tenant::create();
tenancy()->initialize($tenant);
tenancy()->end();
$output = [];
tenancy()->$method(function ($data) use (&$output) {
$output = $data;
});
assertTenancyInitializedAndEnded($output, $tenant);
})->with([
'dump',
'dd',
]);
test('tenancy can log events immediately', function () {
// todo implement
pest()->markTestIncomplete();
});
// todo test the different behavior of the methods in different contexts, or get rid of the logic and simplify it
function assertTenancyInitializedAndEnded(array $log, Tenant $tenant): void
{
expect($log)->toHaveCount(4);
expect($log[0]['event'])->toBe(InitializingTenancy::class);
expect($log[0]['tenant'])->toBe($tenant);
expect($log[1]['event'])->toBe(TenancyInitialized::class);
expect($log[1]['tenant'])->toBe($tenant);
expect($log[2]['event'])->toBe(EndingTenancy::class);
expect($log[2]['tenant'])->toBe($tenant);
expect($log[3]['event'])->toBe(TenancyEnded::class);
expect($log[3]['tenant'])->toBe($tenant);
}

View file

@ -2,12 +2,13 @@
declare(strict_types=1);
namespace Stancl\Tenancy\Tests\Etc;
namespace Stancl\Tenancy\Tests\Etc\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Stancl\Tenancy\Concerns\HasATenantsOption;
use Stancl\Tenancy\Concerns\TenantAwareCommand;
use Stancl\Tenancy\Tests\Etc\User;
class AddUserCommand extends Command
{

View file

@ -2,7 +2,7 @@
declare(strict_types=1);
namespace Stancl\Tenancy\Tests\Etc;
namespace Stancl\Tenancy\Tests\Etc\Console;
use Orchestra\Testbench\Foundation\Console\Kernel;
@ -10,6 +10,7 @@ class ConsoleKernel extends Kernel
{
protected $commands = [
ExampleCommand::class,
ExampleQuestionCommand::class,
AddUserCommand::class,
];
}

View file

@ -2,7 +2,7 @@
declare(strict_types=1);
namespace Stancl\Tenancy\Tests\Etc;
namespace Stancl\Tenancy\Tests\Etc\Console;
use Illuminate\Console\Command;

View file

@ -0,0 +1,46 @@
<?php
namespace Stancl\Tenancy\Tests\Etc\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Stancl\Tenancy\Tests\Etc\User;
class ExampleQuestionCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'user:addwithname {name}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$email = $this->ask('What is your email?');
User::create([
'name' => $this->argument('name'),
'email' => $email,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
]);
$this->line("User created: ". $this->argument('name') . "($email)");
return 0;
}
}

View file

@ -4,7 +4,7 @@ declare(strict_types=1);
namespace Stancl\Tenancy\Tests\Etc;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;
use Stancl\Tenancy\Database\Models;

View file

@ -181,7 +181,7 @@ test('database is not migrated if creation is disabled', function () {
class FooListener extends QueueableListener
{
public static $shouldQueue = false;
public static bool $shouldQueue = false;
public function handle()
{

View file

@ -14,6 +14,28 @@ afterEach(function () {
TenantConfig::$storageToConfigMap = [];
});
test('nested tenant values are merged', function () {
expect(config('whitelabel.theme'))->toBeNull();
config([
'tenancy.features' => [TenantConfig::class],
'tenancy.bootstrappers' => [],
]);
Event::listen(TenancyInitialized::class, BootstrapTenancy::class);
Event::listen(TenancyEnded::class, RevertToCentralContext::class);
TenantConfig::$storageToConfigMap = [
'whitelabel.config.theme' => 'whitelabel.theme',
];
$tenant = Tenant::create([
'whitelabel' => ['config' => ['theme' => 'dark']],
]);
tenancy()->initialize($tenant);
expect(config('whitelabel.theme'))->toBe('dark');
tenancy()->end();
});
test('config is merged and removed', function () {
expect(config('services.paypal'))->toBe(null);
config([

View file

@ -18,7 +18,11 @@ beforeEach(function () {
], function () {
Route::get('/foo/{a}/{b}', function ($a, $b) {
return "$a + $b";
});
})->name('foo');
Route::get('/baz/{a}/{b}', function ($a, $b) {
return "$a - $b";
})->name('baz');
});
});
@ -123,3 +127,23 @@ test('tenant parameter name can be customized', function () {
->withoutExceptionHandling()
->get('/acme/foo/abc/xyz');
});
test('tenant parameter is set for all routes as the default parameter once the tenancy initialized', function () {
Tenant::create([
'id' => 'acme',
]);
expect(tenancy()->initialized)->toBeFalse();
// make a request that will initialize tenancy
pest()->get(route('foo', ['tenant' => 'acme', 'a' => 1, 'b' => 2]));
expect(tenancy()->initialized)->toBeTrue();
expect(tenant('id'))->toBe('acme');
// assert that the route WITHOUT the tenant parameter matches the route WITH the tenant parameter
expect(route('baz', ['a' => 1, 'b' => 2]))->toBe(route('baz', ['tenant' => 'acme', 'a' => 1, 'b' => 2]));
expect(route('baz', ['a' => 1, 'b' => 2]))->toBe('http://localhost/acme/baz/1/2'); // assert the full route string
pest()->get(route('baz', ['a' => 1, 'b' => 2]))->assertOk(); // Assert route don't need tenant parameter
});

View file

@ -15,7 +15,7 @@ use Stancl\Tenancy\Contracts\SyncMaster;
use Stancl\Tenancy\Database\Concerns\CentralConnection;
use Stancl\Tenancy\Database\Concerns\ResourceSyncing;
use Stancl\Tenancy\Database\Models\TenantPivot;
use Stancl\Tenancy\DatabaseConfig;
use Stancl\Tenancy\Database\DatabaseConfig;
use Stancl\Tenancy\Events\SyncedResourceChangedInForeignDatabase;
use Stancl\Tenancy\Events\SyncedResourceSaved;
use Stancl\Tenancy\Events\TenancyEnded;
@ -575,7 +575,7 @@ class CentralUser extends Model implements SyncMaster
return ResourceUser::class;
}
public function getGlobalIdentifierKey()
public function getGlobalIdentifierKey(): string|int
{
return $this->getAttribute($this->getGlobalIdentifierKeyName());
}
@ -610,7 +610,7 @@ class ResourceUser extends Model implements Syncable
public $timestamps = false;
public function getGlobalIdentifierKey()
public function getGlobalIdentifierKey(): string|int
{
return $this->getAttribute($this->getGlobalIdentifierKeyName());
}

View file

@ -94,6 +94,18 @@ test('asset helper tenancy can be disabled', function () {
expect(asset('foo'))->toBe($original);
});
test('test asset controller returns a 404 when no path is provided', function () {
TenantAssetsController::$tenancyMiddleware = InitializeTenancyByRequestData::class;
$tenant = Tenant::create();
tenancy()->initialize($tenant);
pest()->get(tenant_asset(null), [
'X-Tenant' => $tenant->id,
])->assertNotFound();
});
function getEnvironmentSetUp($app)
{
$app->booted(function () {

View file

@ -12,16 +12,16 @@ use Stancl\Tenancy\Database\DatabaseManager;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Database\Exceptions\TenantDatabaseAlreadyExistsException;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLDatabaseManager;
use Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager;
use Stancl\Tenancy\TenantDatabaseManagers\SQLiteDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\MicrosoftSQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\MySQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\PermissionControlledMySQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLDatabaseManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager;
use Stancl\Tenancy\Database\TenantDatabaseManagers\SQLiteDatabaseManager;
use Stancl\Tenancy\Tests\Etc\Tenant;
test('databases can be created and deleted', function ($driver, $databaseManager) {
@ -135,7 +135,7 @@ test('db name is prefixed with db path when sqlite is used', function () {
test('schema manager uses schema to separate tenant dbs', function () {
config([
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
'tenancy.database.managers.pgsql' => \Stancl\Tenancy\Database\TenantDatabaseManagers\PostgreSQLSchemaManager::class,
'tenancy.boostrappers' => [
DatabaseTenancyBootstrapper::class,
],

View file

@ -157,23 +157,25 @@ class AnotherTenant extends Model implements Contracts\Tenant
return 'id';
}
public function getTenantKey()
public function getTenantKey(): int|string
{
return $this->getAttribute('id');
}
public function run(callable $callback)
public function run(Closure $callback): mixed
{
$callback();
}
public function getInternal(string $key)
public function getInternal(string $key): mixed
{
return $this->$key;
}
public function setInternal(string $key, $value)
public function setInternal(string $key, mixed $value): static
{
$this->$key = $value;
return $this;
}
}

View file

@ -4,25 +4,27 @@ declare(strict_types=1);
use Carbon\Carbon;
use Carbon\CarbonInterval;
use Illuminate\Support\Str;
use Illuminate\Auth\TokenGuard;
use Illuminate\Auth\SessionGuard;
use Stancl\JobPipeline\JobPipeline;
use Illuminate\Support\Facades\Auth;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Stancl\JobPipeline\JobPipeline;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Database\Models\ImpersonationToken;
use Stancl\Tenancy\Events\TenancyEnded;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Features\UserImpersonation;
use Stancl\Tenancy\Jobs\CreateDatabase;
use Stancl\Tenancy\Events\TenantCreated;
use Stancl\Tenancy\Events\TenancyInitialized;
use Stancl\Tenancy\Features\UserImpersonation;
use Stancl\Tenancy\Listeners\BootstrapTenancy;
use Stancl\Tenancy\Listeners\RevertToCentralContext;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Stancl\Tenancy\Tests\Etc\Tenant;
use Illuminate\Foundation\Auth\User as Authenticable;
use Stancl\Tenancy\Database\Models\ImpersonationToken;
use Stancl\Tenancy\Middleware\InitializeTenancyByPath;
use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;
use Stancl\Tenancy\Bootstrappers\DatabaseTenancyBootstrapper;
use Stancl\Tenancy\Exceptions\StatefulGuardRequiredException;
beforeEach(function () {
pest()->artisan('migrate', [
@ -223,6 +225,46 @@ test('impersonation works with multiple models and guards', function () {
});
});
test('impersonation tokens can be created only with stateful guards', function () {
config([
'auth.guards' => [
'nonstateful' => [
'driver' => 'nonstateful',
'provider' => 'provider',
],
'stateful' => [
'driver' => 'session',
'provider' => 'provider',
],
],
'auth.providers.provider' => [
'driver' => 'eloquent',
'model' => ImpersonationUser::class,
],
]);
$tenant = Tenant::create();
migrateTenants();
$user = $tenant->run(function () {
return ImpersonationUser::create([
'name' => 'Joe',
'email' => 'joe@local',
'password' => bcrypt('secret'),
]);
});
Auth::extend('nonstateful', fn($app, $name, array $config) => new TokenGuard(Auth::createUserProvider($config['provider']), request()));
expect(fn() => tenancy()->impersonate($tenant, $user->id, '/dashboard', 'nonstateful'))
->toThrow(StatefulGuardRequiredException::class);
Auth::extend('stateful', fn ($app, $name, array $config) => new SessionGuard($name, Auth::createUserProvider($config['provider']), session()));
expect(tenancy()->impersonate($tenant, $user->id, '/dashboard', 'stateful'))
->toBeInstanceOf(ImpersonationToken::class);
});
function migrateTenants()
{
pest()->artisan('tenants:migrate')->assertExitCode(0);

View file

@ -48,11 +48,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
protected function getEnvironmentSetUp($app)
{
if (file_exists(__DIR__ . '/../.env')) {
if (method_exists(\Dotenv\Dotenv::class, 'createImmutable')) {
\Dotenv\Dotenv::createImmutable(__DIR__ . '/..')->load();
} else {
\Dotenv\Dotenv::create(__DIR__ . '/..')->load();
}
\Dotenv\Dotenv::createImmutable(__DIR__ . '/..')->load();
}
$app['config']->set([
@ -100,7 +96,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
'--realpath' => true,
'--force' => true,
],
'tenancy.bootstrappers.redis' => \Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper::class,
'tenancy.bootstrappers.redis' => \Stancl\Tenancy\Bootstrappers\RedisTenancyBootstrapper::class, // todo0 change this to []? two tests in TenantDatabaseManagerTest are failing with that
'queue.connections.central' => [
'driver' => 'sync',
'central' => true,
@ -146,7 +142,7 @@ abstract class TestCase extends \Orchestra\Testbench\TestCase
*/
protected function resolveApplicationConsoleKernel($app)
{
$app->singleton('Illuminate\Contracts\Console\Kernel', Etc\ConsoleKernel::class);
$app->singleton('Illuminate\Contracts\Console\Kernel', Etc\Console\ConsoleKernel::class);
}
public function randomString(int $length = 10)