89 lines
2.2 KiB
PHP
89 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Tests\Feature;
|
|
|
|
use App\Support\MissingTenantContextException;
|
|
use App\Support\TenantContext;
|
|
use Illuminate\Database\Schema\Blueprint;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Tests\Fixtures\TenantProbe;
|
|
use Tests\TestCase;
|
|
|
|
class TenantScopeTest extends TestCase
|
|
{
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
Schema::dropIfExists('tenant_probes');
|
|
Schema::create('tenant_probes', function (Blueprint $table): void {
|
|
$table->id();
|
|
$table->string('tenant_code', 32);
|
|
$table->string('name');
|
|
$table->timestamps();
|
|
});
|
|
}
|
|
|
|
protected function tearDown(): void
|
|
{
|
|
Schema::dropIfExists('tenant_probes');
|
|
|
|
parent::tearDown();
|
|
}
|
|
|
|
public function test_queries_only_return_the_current_tenant(): void
|
|
{
|
|
$context = app(TenantContext::class);
|
|
|
|
$context->set('tenant-a');
|
|
TenantProbe::query()->create(['name' => 'alpha']);
|
|
|
|
$context->set('tenant-b');
|
|
TenantProbe::query()->create(['name' => 'beta']);
|
|
|
|
$context->set('tenant-a');
|
|
|
|
$this->assertSame(['alpha'], TenantProbe::query()->pluck('name')->all());
|
|
}
|
|
|
|
public function test_create_always_uses_the_current_tenant(): void
|
|
{
|
|
app(TenantContext::class)->set('tenant-a');
|
|
|
|
TenantProbe::query()->create([
|
|
'name' => 'alpha',
|
|
'tenant_code' => 'tenant-b',
|
|
]);
|
|
|
|
$this->assertDatabaseHas('tenant_probes', [
|
|
'name' => 'alpha',
|
|
'tenant_code' => 'tenant-a',
|
|
]);
|
|
}
|
|
|
|
public function test_tenant_code_cannot_be_reassigned(): void
|
|
{
|
|
app(TenantContext::class)->set('tenant-a');
|
|
|
|
$row = TenantProbe::query()->create(['name' => 'alpha']);
|
|
$row->tenant_code = 'tenant-b';
|
|
$row->name = 'renamed';
|
|
$row->save();
|
|
|
|
$this->assertDatabaseHas('tenant_probes', [
|
|
'id' => $row->id,
|
|
'tenant_code' => 'tenant-a',
|
|
'name' => 'renamed',
|
|
]);
|
|
}
|
|
|
|
public function test_query_without_context_fails_closed(): void
|
|
{
|
|
$this->expectException(MissingTenantContextException::class);
|
|
|
|
TenantProbe::query()->get();
|
|
}
|
|
}
|