Files
ucvl-zonghengjia-open-source/backend/control/tests/test_plan_catalog.py
T
2026-10-11 23:23:20 +00:00

172 lines
9.6 KiB
Python

from decimal import Decimal
from io import StringIO
from django.core.exceptions import ValidationError
from django.core.management import call_command
from django.core.management.base import CommandError
from django.db import IntegrityError, transaction
from django.test import TestCase, override_settings
from django.urls import reverse
from accounts.forms import RegistrationForm
from accounts.models import User
from control.forms import PlanApplicationForm
from control.models import Node, Plan, PlanApplication, PlanCatalogDraft, Subscription
from control.plan_catalog import proposed_catalog
from control.services import desired_subscriptions_for_node
@override_settings(SECURE_SSL_REDIRECT=False, WECOM_ENABLED=False,
STORAGES={"default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
"staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}})
class PlanCatalogDraftTests(TestCase):
def setUp(self):
self.employee = User.objects.create_user(username="catalog-employee", email="catalog-employee@example.invalid", identity_type="employee", account_status="active")
self.external = User.objects.create_user(username="catalog-external", email="catalog-external@example.invalid", account_status="active")
self.admin = User.objects.create_superuser(username="catalog-admin", email="catalog@example.invalid", password="fixture")
call_command("prepare_monthly_1024g", list_plan=True, stdout=StringIO())
self.original = Plan.objects.get(slug="monthly-1024g")
def seed(self):
call_command("prepare_plan_catalog", create=True, stdout=StringIO())
def test_default_is_read_only_preview(self):
output = StringIO()
call_command("prepare_plan_catalog", stdout=output)
self.assertIn("共19项", output.getvalue())
self.assertIn("仅预览,未写入", output.getvalue())
self.assertEqual(PlanCatalogDraft.objects.count(), 0)
def test_exactly_twelve_additional_personal_quotas_plus_unlimited(self):
self.seed()
personal = PlanCatalogDraft.objects.filter(scope="personal")
self.assertEqual(personal.count(), 13)
self.assertEqual(personal.filter(traffic_limit_gb__gt=0).count(), 12)
self.assertEqual(personal.filter(traffic_limit_gb=1024).count(), 0)
self.assertEqual(personal.filter(traffic_limit_gb=0).count(), 1)
self.assertEqual(personal.exclude(member_limit=1, device_limit=3).count(), 0)
self.assertEqual(personal.filter(price_cny__isnull=True).count(), 13)
def test_team_quota_and_caps_are_per_member_proposals_not_confirmed_prices(self):
self.seed()
teams = PlanCatalogDraft.objects.filter(scope="team")
self.assertSetEqual(set(teams.values_list("traffic_limit_gb", flat=True)), {0, 3*1024, 5*1024, 10*1024, 20*1024, 50*1024})
for draft in teams:
self.assertIsNone(draft.price_cny)
if draft.traffic_limit_gb:
self.assertEqual(draft.traffic_limit_gb, draft.member_limit * 1024)
self.assertEqual(draft.device_limit, draft.member_limit * 3)
self.assertEqual(draft.concurrent_limit, draft.member_limit * 2)
else:
self.assertIsNone(draft.member_limit)
self.assertIsNone(draft.device_limit)
self.assertIsNone(draft.concurrent_limit)
self.assertIn("共享账本尚未接入", draft.description)
def test_seed_idempotent_and_preserves_admin_pricing_and_notes(self):
self.seed()
draft = PlanCatalogDraft.objects.get(slug="team-monthly-20-members")
draft.price_cny = Decimal("100.00") # synthetic proposal, not a released price
draft.member_limit, draft.device_limit, draft.concurrent_limit = 20, 40, 10
draft.name, draft.description = "管理员草案", "人工确认内容"
draft.save()
before = list(PlanCatalogDraft.objects.values())
self.seed()
self.assertEqual(list(PlanCatalogDraft.objects.values()), before)
self.assertEqual(PlanCatalogDraft.objects.count(), 19)
def test_conflicting_quota_rolls_back_whole_seed_batch(self):
spec = proposed_catalog()[-1].copy()
spec["traffic_limit_gb"] = 42
conflict = PlanCatalogDraft.objects.create(**spec)
with self.assertRaises(CommandError):
self.seed()
self.assertEqual(PlanCatalogDraft.objects.count(), 1)
conflict.refresh_from_db()
self.assertEqual(conflict.traffic_limit_gb, 42)
def test_original_plans_subscriptions_usage_and_tokens_are_unchanged(self):
subscription = PlanApplication.submit(user=self.employee, plan=self.original).approve(self.admin)
Subscription.objects.filter(pk=subscription.pk).update(upload_bytes=12345, download_bytes=67890)
before_plans = list(Plan.objects.values())
before_subscriptions = list(Subscription.objects.values())
before_applications = list(PlanApplication.objects.values())
self.seed()
self.assertEqual(list(Plan.objects.values()), before_plans)
self.assertEqual(list(Subscription.objects.values()), before_subscriptions)
self.assertEqual(list(PlanApplication.objects.values()), before_applications)
self.original.refresh_from_db()
self.assertEqual(self.original.price_cny, Decimal("8.00"))
self.assertEqual(self.original.traffic_limit_gb, 1024)
def test_drafts_never_enter_registration_application_or_node_configuration(self):
before_register = list(RegistrationForm().fields["plan"].queryset.values_list("pk", flat=True))
before_apply = list(PlanApplicationForm(user=self.external).fields["plan"].queryset.values_list("pk", flat=True))
self.seed()
self.assertEqual(list(RegistrationForm().fields["plan"].queryset.values_list("pk", flat=True)), before_register)
self.assertEqual(list(PlanApplicationForm(user=self.external).fields["plan"].queryset.values_list("pk", flat=True)), before_apply)
node = Node.objects.create(name="fixture", slug="catalog-fixture", server="example.invalid", port=11082)
self.assertFalse(desired_subscriptions_for_node(node).exists())
self.assertEqual(PlanApplication.objects.count(), 0)
def test_external_cannot_read_draft_admin(self):
self.seed()
self.client.force_login(self.external)
response = self.client.get(reverse("admin:control_plancatalogdraft_changelist"))
self.assertEqual(response.status_code, 302)
self.assertIn("/admin/login/", response.url)
response = self.client.get(reverse("portal-dashboard"))
self.assertNotContains(response, "团队无限流量月度套餐")
self.assertNotContains(response, "个人无限流量月度套餐")
def test_admin_sees_pending_not_free_and_cannot_publish_from_draft(self):
self.seed()
self.client.force_login(self.admin)
response = self.client.get(reverse("admin:control_plancatalogdraft_changelist"))
self.assertContains(response, "待定价", count=19)
self.assertContains(response, "仅草稿 · 未上架 · 不收款")
draft = PlanCatalogDraft.objects.get(slug="team-monthly-unlimited")
response = self.client.get(reverse("admin:control_plancatalogdraft_change", args=[draft.pk]))
self.assertContains(response, "团队成员共享账本尚未接入")
self.assertNotContains(response, 'name="active"')
def test_unlimited_and_pending_labels(self):
draft = PlanCatalogDraft(**proposed_catalog()[-1])
self.assertEqual(draft.quota_label, "无限代理流量")
self.assertEqual(draft.price_label, "待定价")
draft.traffic_limit_gb = 20 * 1024
self.assertEqual(draft.quota_label, "20 TB/月")
draft.price_cny = Decimal("8.00")
self.assertIn("草稿", draft.price_label)
def test_validation_rejects_negative_price_zero_caps_and_invalid_personal_seats(self):
for field, value in (("price_cny", Decimal("-1")), ("member_limit", 0), ("device_limit", 0), ("concurrent_limit", 0), ("member_limit", 2), ("concurrent_limit", 4)):
with self.subTest(field=field, value=value):
draft = PlanCatalogDraft(**proposed_catalog()[0])
setattr(draft, field, value)
with self.assertRaises(ValidationError):
draft.full_clean()
def test_database_rejects_negative_price_or_zero_limits(self):
for field, value in (("price_cny", -1), ("member_limit", 0), ("device_limit", 0), ("concurrent_limit", 0)):
with self.subTest(field=field):
spec = proposed_catalog()[0].copy()
spec[field] = value
with self.assertRaises(IntegrityError), transaction.atomic():
PlanCatalogDraft.objects.create(**spec)
def test_live_unlimited_plan_keeps_expiry_and_device_limit_and_tracks_usage(self):
# Exercise existing unlimited semantics without publishing the new draft.
plan = Plan.objects.create(name="Unlimited fixture", slug="unlimited-fixture", traffic_limit_gb=0,
billing_months=1, duration_days=0, device_limit=3)
subscription = PlanApplication.submit(user=self.employee, plan=plan).approve(self.admin)
subscription.provisioning_state = "active"
subscription.upload_bytes = 50 * 1024**4
subscription.save()
self.assertIsNone(subscription.remaining_bytes)
self.assertEqual(subscription.usage_percent, 0)
self.assertEqual(subscription.device_limit, 3)
self.assertIsNotNone(subscription.expires_at)
self.assertEqual(subscription.used_bytes, 50 * 1024**4)
self.assertTrue(subscription.is_usable)