You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/tests/CloudPlanDefinitionTest.php

143 lines
9.9 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Models {
// This focused test intentionally has no database or application bootstrap.
class Model {
private array $testAttributes = [];
public function __get(string $name) { return $this->testAttributes[$name] ?? null; }
public function __set(string $name, $value): void { $this->testAttributes[$name] = $value; }
}
require dirname(__DIR__) . '/app/Models/Shop.php';
}
namespace {
use App\Models\Shop;
$assert = static function ($condition, $message) {
if (!$condition) {
throw new \RuntimeException($message);
}
};
$input = ['name' => 'Cloud starter', 'price' => '19.90', 'cpu_cores' => '2', 'memory_gb' => '2',
'bandwidth_mbps' => '100', 'disk_gib' => '20', 'validity_days' => '30', 'traffic_tb' => '1',
'status' => '1', 'stock' => '-1', 'sort' => '0'];
$data = Shop::validatePlan($input);
$assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20 && $data['price'] === '19.90'
&& $data['memory_mib'] === 2048 && $data['validity_days'] === 30
&& $data['traffic_quota_bytes'] === Shop::TIB,
'GB/TB plan values were not normalized to the existing MiB/byte storage schema.');
$oneUnitPlan = Shop::validatePlan(array_replace($input, ['memory_gb' => '1', 'traffic_tb' => '1']));
$assert($oneUnitPlan['memory_mib'] === 1024 && $oneUnitPlan['traffic_quota_bytes'] === Shop::TIB,
'Entering 1 in the administrator editor must mean 1 GB of memory and 1 TB of traffic.');
$assert(!array_key_exists('class', $data) && !array_key_exists('expire', $data)
&& !array_key_exists('memory_gb', $data) && !array_key_exists('traffic_tb', $data),
'A cloud plan contains presentation units instead of canonical stored entitlements.');
$halfGB = Shop::validatePlan(array_replace($input, ['memory_gb' => '0.5', 'traffic_tb' => '0.0009765625']));
$assert($halfGB['memory_mib'] === 512 && $halfGB['traffic_quota_bytes'] === Shop::GIB,
'Existing half-GB memory or one-GiB traffic values cannot round-trip through the GB/TB editor.');
$displayPlan = new Shop();
$displayPlan->cpu_cores = 2; $displayPlan->memory_mib = 1536; $displayPlan->bandwidth_mbps = 100;
$displayPlan->disk_gib = 20; $displayPlan->validity_days = 30; $displayPlan->traffic_quota_bytes = 2 * Shop::TIB;
$assert($displayPlan->memoryGB() === '1.5' && $displayPlan->trafficTB() === '2'
&& str_contains($displayPlan->content(), '1.5 GB 内存')
&& str_contains($displayPlan->content(), '2 TB 流量'),
'Plan content does not present stored resources in GB/TB.');
foreach (['cpu_cores' => 0, 'memory_gb' => '0.75', 'disk_gib' => 4097, 'bandwidth_mbps' => 0,
'validity_days' => 0, 'traffic_tb' => '0.001', 'price' => '1.999', 'status' => 2,
'stock' => -2, 'name' => ''] as $key => $invalid) {
try {
Shop::validatePlan(array_replace($input, [$key => $invalid]));
throw new \RuntimeException('Invalid plan value accepted: ' . $key);
} catch (\InvalidArgumentException $exception) {
// Expected.
}
}
$source = file_get_contents(dirname(__DIR__) . '/app/Controllers/UserController.php');
$start = strpos($source, 'public function buy(');
$end = strpos($source, 'public function bought(', $start);
$body = substr($source, $start, $end - $start);
$assert(strpos($body, '409') !== false && strpos($body, 'save(') === false && strpos($body, 'transaction(') === false,
'Purchase must not debit or create an order before virtualization integration.');
$controller = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudApiController.php');
$routes = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php');
$cloudSchema = file_get_contents(dirname(__DIR__) . '/sql/cloud.sql');
$client = file_get_contents(dirname(__DIR__) . '/public/cloud/runtime.js');
$shopController = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/ShopController.php');
$shopViews = file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/create.tpl')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/edit.tpl')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/index.tpl');
$invoiceView = file_get_contents(dirname(__DIR__) . '/resources/views/venix/cloud/pages/invoices.tpl');
$invoiceService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoiceService.php');
$invoicePaymentService = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudInvoicePaymentService.php');
$paymentProviders = implode("\n", [
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/YipayPaymentService.php'),
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/PaytaroPaymentService.php'),
file_get_contents(dirname(__DIR__) . '/app/Services/Payment/UsdtPaymentService.php'),
]);
$assert(str_contains($controller, '\'can_operate\' => $canOperate')
&& str_contains($controller, '\'can_delete\' => $canDelete')
&& str_contains($controller, '$canOperate = $canDelete && $instance->serviceAvailable()')
&& str_contains($controller, '\'can_view_credential\' => $owner || $global')
&& str_contains($client, '!vm.can_view_credential')
&& str_contains($client, "vm.is_owner || vm.can_delete")
&& str_contains($client, "if (vm.can_delete) danger.append(actionButton('删除虚拟机'")
&& str_contains($client, "if (!vm?.can_operate)")
&& str_contains($client, "if (!vm?.can_delete)"),
'VM operation, deletion, ownership and credential capabilities were not kept separate.');
$capabilityStart = strpos($controller, '$canOperate =');
$capabilityEnd = strpos($controller, 'return array_merge', $capabilityStart);
$capabilityBody = substr($controller, $capabilityStart,
$capabilityEnd - $capabilityStart);
$assert(!str_contains($capabilityBody, 'network_status'),
'Traffic-only network suspension must not remove instance power or console controls.');
$assert(str_contains($controller, '$suffix === \'/rescue/exit\'')
&& str_contains($controller, "['blocking', 'blocked_traffic', 'blocked_expired', 'block_failed']"),
'Rescue exit does not preserve the authoritative traffic suspension target.');
$assert(str_contains($controller, "\$body['delete_disks'] ?? true")
&& str_contains($controller, "\$instance->service_status !== 'exempt' && !\$deleteDisks")
&& str_contains($controller, '销售实例删除必须同步删除面板管理的虚拟磁盘'),
'Tenant deletion must not leave an unmanaged system disk that expiry cleanup can no longer reach.');
$assert(preg_match('/[\'\"]deletion_at[\'\"]\s*=>/', $invoiceService) === 1
&& preg_match('/[\'\"]payable[\'\"]\s*=>/', $invoiceService) === 1
&& str_contains($invoiceService, 'paymentDeadlinePassed'),
'Invoice API output must expose its deletion deadline and authoritative payable flag.');
$assert(str_contains($client, 'const payable = invoiceCanPay(invoice);')
&& str_contains($client, 'if (payable)')
&& str_contains($client, '已超过支付截止时间'),
'Expired invoice rows must not render a balance or provider payment action.');
$assert(str_contains($routes, "['GET', 'POST'], '/invoices'")
&& str_contains($routes, "'/invoices/by-request/{key:[A-Za-z0-9_.-]+}'")
&& str_contains($controller, 'private function createProvisionInvoice')
&& str_contains($controller, "CloudOrder::where('user_id', \$actor['user_id'])")
&& str_contains($controller, "CloudInvoice::where('order_id', \$order->id)"),
'Opening invoices must use the unified invoice API and owner-scoped lost-response recovery.');
$assert(str_contains($invoicePaymentService, 'assertInvoicePaymentAllowed')
&& substr_count($paymentProviders,
'CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser)') === 3,
'Every online provider must recheck account restrictions inside its final row-locked order transaction.');
$assert(str_contains($shopViews, '内存(GB)')
&& str_contains($shopViews, '每期流量额度(TB)')
&& str_contains($shopViews, '价格(USD)')
&& !str_contains($shopViews, '内存(MiB)')
&& !str_contains($shopViews, '每期流量额度(GiB)')
&& str_contains($shopController, "'memory_gb' => \$shop->memoryGB()")
&& str_contains($shopController, "'traffic_tb' => \$shop->trafficTB()")
&& str_contains($shopController, "return '$' . number_format"),
'The administrator plan editor/list must use GB, TB and USD while preserving canonical storage.');
$assert(str_contains($client, 'function formatUsd(value)')
&& str_contains($client, 'formatUsd(plan.price)')
&& str_contains($client, 'formatUsd(invoice.amount)')
&& str_contains($client, 'formatUsd(payload.balance)')
&& !str_contains($client, '¥') && !str_contains($invoiceView, '¥')
&& str_contains($invoiceView, '$—'),
'Deployment and cloud billing must consistently present stored monetary values as USD.');
$assert(str_contains($cloudSchema, "purpose VARCHAR(16) NOT NULL DEFAULT 'renewal'")
&& str_contains($cloudSchema, 'order_id BIGINT UNSIGNED DEFAULT NULL')
&& str_contains($cloudSchema, 'UNIQUE KEY uniq_cloud_invoice_order (order_id)')
&& str_contains($cloudSchema, 'payload_cipher LONGTEXT DEFAULT NULL')
&& str_contains($cloudSchema, 'ALTER TABLE cloud_invoices MODIFY instance_id BIGINT UNSIGNED NULL')
&& str_contains($cloudSchema, 'ALTER TABLE cloud_invoices MODIFY renews_expires_at BIGINT UNSIGNED NULL'),
'Fresh and upgraded schemas must support unpaid provisioning invoices without a fake instance.');
echo 'Cloud plan definition checks passed.' . PHP_EOL;
}