Files
portal/app/tests/Feature/Api/V1/PublicDealsApiTest.php
T
Дмитрий 1fd24745d1 test(G6): приёмка публичного API сделок (RED)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 10:11:24 +03:00

108 lines
3.9 KiB
PHP

<?php
declare(strict_types=1);
use App\Models\ApiKey;
use App\Models\Deal;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Tests\Concerns\SharesSupplierPdo;
uses(DatabaseTransactions::class, SharesSupplierPdo::class);
/** Создаёт активный read-ключ, возвращает plain-ключ. */
function makeApiKey(int $tenantId, int $userId, array $over = []): string
{
$plain = 'lpkapi_'.Str::random(48);
ApiKey::create(array_merge([
'tenant_id' => $tenantId,
'user_id' => $userId,
'name' => 'test',
'key_hash' => Hash::make($plain),
'key_prefix' => substr($plain, 0, 10),
'scopes' => ['read'],
'expires_at' => now()->addYear(),
'is_active' => true,
'created_at' => now(),
], $over));
return $plain;
}
test('валидный ключ → 200 и только свои сделки', function () {
$tenantA = Tenant::factory()->create();
$userA = User::factory()->create(['tenant_id' => $tenantA->id]);
$tenantB = Tenant::factory()->create();
Deal::factory()->count(2)->create(['tenant_id' => $tenantA->id, 'received_at' => now()]);
Deal::factory()->create(['tenant_id' => $tenantB->id, 'received_at' => now()]);
$key = makeApiKey($tenantA->id, $userA->id);
$r = $this->getJson('/api/v1/deals', ['Authorization' => "Bearer {$key}"]);
$r->assertOk();
expect($r->json('data'))->toHaveCount(2);
});
test('нет заголовка → 401', function () {
$this->getJson('/api/v1/deals')->assertStatus(401);
});
test('неверный ключ → 401', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create(['tenant_id' => $tenant->id]);
$key = makeApiKey($tenant->id, $user->id);
// Тот же префикс, но изменённый хвост — Hash::check не пройдёт.
$bad = substr($key, 0, 10).str_repeat('x', strlen($key) - 10);
$this->getJson('/api/v1/deals', ['Authorization' => "Bearer {$bad}"])->assertStatus(401);
});
test('просроченный ключ → 401', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create(['tenant_id' => $tenant->id]);
$key = makeApiKey($tenant->id, $user->id, ['expires_at' => now()->subDay()]);
$this->getJson('/api/v1/deals', ['Authorization' => "Bearer {$key}"])->assertStatus(401);
});
test('неактивный ключ → 401', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create(['tenant_id' => $tenant->id]);
$key = makeApiKey($tenant->id, $user->id, ['is_active' => false]);
$this->getJson('/api/v1/deals', ['Authorization' => "Bearer {$key}"])->assertStatus(401);
});
test('last_used_at обновляется после успешного запроса', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create(['tenant_id' => $tenant->id]);
$key = makeApiKey($tenant->id, $user->id, ['last_used_at' => null]);
$this->getJson('/api/v1/deals', ['Authorization' => "Bearer {$key}"])->assertOk();
$row = ApiKey::where('tenant_id', $tenant->id)->latest('id')->first();
expect($row->last_used_at)->not->toBeNull();
});
test('since-фильтр отсекает старые сделки', function () {
$tenant = Tenant::factory()->create();
$user = User::factory()->create(['tenant_id' => $tenant->id]);
Deal::factory()->create(['tenant_id' => $tenant->id, 'received_at' => now()]);
Deal::factory()->create(['tenant_id' => $tenant->id, 'received_at' => now()->subDays(10)]);
$key = makeApiKey($tenant->id, $user->id);
$since = now()->subDays(2)->toDateString();
$r = $this->getJson("/api/v1/deals?since={$since}", ['Authorization' => "Bearer {$key}"]);
$r->assertOk();
expect($r->json('data'))->toHaveCount(1);
});