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

175 lines
12 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', 'cpu_cores' => '2', 'memory_gb' => '2',
'bandwidth_mbps' => '100', 'disk_gib' => '20', 'validity_days' => '30', 'traffic_tb' => '1',
'status' => '1', 'sort' => '0'];
$data = Shop::validatePlan($input);
$assert($data['cpu_cores'] === 2 && $data['disk_gib'] === 20
&& $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('host_id', $data) && !array_key_exists('price', $data)
&& !array_key_exists('stock', $data)
&& !array_key_exists('memory_gb', $data) && !array_key_exists('traffic_tb', $data),
'A base plan contains placement, pricing, stock, or presentation-only fields.');
$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', 'status' => 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');
$legacyRoutes = file_get_contents(dirname(__DIR__) . '/config/routes.php');
$assert(!str_contains($source, 'public function buy(')
&& !str_contains($legacyRoutes, "post('/buy'"),
'Retired legacy purchase endpoint remains available.');
$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')
. "\n" . file_get_contents(dirname(__DIR__)
. '/public/cloud/invoice-detail-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')
. file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/shop/offer_form.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');
$invoicePresentation = file_get_contents(dirname(__DIR__)
. '/app/Services/Cloud/CloudInvoicePresentation.php');
$invoicePageService = file_get_contents(dirname(__DIR__)
. '/app/Services/Cloud/CloudInvoicePageService.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($routes, "map(['GET', 'POST'], '/invoices'")
&& str_contains($controller, 'createProvisionInvoice('),
'Cloud invoice checkout must remain the only supported purchase entry point.');
$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.');
$rescueExitStart = strpos($controller, "if (\$action === '/exit')");
$rescueExitEnd = $rescueExitStart === false ? false
: strpos($controller, '} else {', $rescueExitStart);
$rescueExit = $rescueExitStart === false || $rescueExitEnd === false
? '' : substr($controller, $rescueExitStart,
$rescueExitEnd - $rescueExitStart);
$assert(str_contains($rescueExit, "\$suffix = '/rescue/exit'")
&& str_contains($rescueExit, "'network_suspended' => in_array(")
&& str_contains($rescueExit, "'ack_data_loss' => true")
&& str_contains($rescueExit, "'blocking'")
&& str_contains($rescueExit, "'blocking_expired'")
&& str_contains($rescueExit, "'blocked_traffic'")
&& str_contains($rescueExit, "'blocked_expired'")
&& str_contains($rescueExit, "'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, 'function invoiceCanPay(invoice)')
&& substr_count($client, 'if (!invoiceCanPay(invoice))') >= 2
&& str_contains($client,
"invoice?.payable === true && invoice?.available_action === 'pay'")
&& str_contains($invoicePresentation,
"(\$invoice['payable'] ?? false) === true"),
'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 availability 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, 'CloudOffer::validateOffer($input)')
&& !str_contains($shopController, "'host_id' => \$shop->host_id"),
'The administrator catalog must keep canonical plan units and move placement/pricing to offers.');
$assert(str_contains($client, 'function formatUsd(value)')
&& str_contains($client, 'formatUsd(instancePrice)')
&& str_contains($client, 'formatUsd(backupPrice)')
&& str_contains($client, 'formatUsd(total)')
&& !str_contains($client, 'formatUsd(offer.price)')
&& str_contains($invoicePresentation,
'CloudBillingPresentationCatalog::money(')
&& str_contains($invoicePageService,
"CloudBillingPresentationCatalog::money(\$balance, 'USD')")
&& !str_contains($client, '¥') && !str_contains($invoiceView, '¥')
&& str_contains($invoiceView, '$cloud_invoice_balance')
&& str_contains($invoiceView, '$invoice.amount_display'),
'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, 'sealed_payload LONGTEXT DEFAULT NULL')
&& !preg_match('/\b(?:ALTER|DROP)\s+TABLE\b/i', $cloudSchema),
'Fresh schema must support unpaid provisioning invoices without upgrade DDL.');
echo 'Cloud plan definition checks passed.' . PHP_EOL;
}