Files
2026-10-17 13:04:35 +07:00

78 lines
2.7 KiB
PHP

<?php
declare(strict_types=1);
namespace Tests\Feature\Api\Service;
use App\Models\Customer;
use App\Models\ModuleVmware;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Tests\TestCase;
class VmMetricsTest extends TestCase
{
use RefreshDatabase;
public function test_customer_can_read_metrics_for_owned_vm(): void
{
$customer = Customer::factory()->create(['status' => 1]);
$vm = ModuleVmware::create([
'customer_id' => $customer->id,
'vmware_id' => 'vm-217208',
'ram_mb' => 2048,
'status' => 1,
]);
config()->set('portal-monitor.url', 'http://portal-monitor-api:8080');
config()->set('portal-monitor.api_key', 'test-api-key');
Http::fake([
'*/api/v1/vsphere/vms/vm-217208/metrics' => Http::response([
'success' => true,
'data' => ['cpu_usage_percent' => 15.5, 'timestamp' => '2026-10-17T04:00:00Z'],
]),
'*/api/v1/vsphere/vms/vm-217208/storage' => Http::response([
'success' => true,
'data' => [
'disks' => [['capacity_bytes' => 10737418240]],
'summary' => [
'total_bytes' => 10420744192,
'used_bytes' => 5787086848,
'usage_percent' => 55.5343,
],
],
]),
]);
$this->actingAs($customer, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->getJson('/v1/system/vm-metrics?product=' . $vm->vmware_id)
->assertOk()
->assertJsonPath('success', true)
->assertJsonPath('data.cpu_usage_percent', 15.5)
->assertJsonPath('data.mem_total_mb', 2048)
->assertJsonPath('data.disk_used_bytes', 5787086848)
->assertJsonPath('data.disk_total_bytes', 10420744192)
->assertJsonPath('data.disk_usage_percent', 55.5343);
}
public function test_customer_cannot_read_another_customers_vm_metrics(): void
{
$owner = Customer::factory()->create(['status' => 1]);
$attacker = Customer::factory()->create(['status' => 1]);
$vm = ModuleVmware::create([
'customer_id' => $owner->id,
'vmware_id' => 'vm-217209',
'status' => 1,
]);
Http::fake();
$this->actingAs($attacker, 'client')
->withHeaders(['x-access-token' => $this->buildClientAccessToken()])
->getJson('/v1/system/vm-metrics?product=' . $vm->vmware_id)
->assertNotFound();
Http::assertNothingSent();
}
}