import io import json from django.contrib.auth import get_user_model from django.core.management import call_command from django.core.management.base import CommandError from django.db import connection from django.test import TestCase, TransactionTestCase from django.db.migrations.executor import MigrationExecutor from control.approval_audit import audit_plan_approvals from control.models import Plan, PlanApplication, Subscription class ApprovalAuditTests(TestCase): def setUp(self): self.owner = get_user_model().objects.create_user(username="audit-owner", email="private@example.invalid") self.plan = Plan.objects.create(name="Private plan", slug="audit-plan", audience="all") def audit(self, **options): queries = [] def readonly(execute, sql, params, many, context): queries.append(sql) self.assertTrue(sql.lstrip().upper().startswith(("SELECT", "PRAGMA")), sql) return execute(sql, params, many, context) with connection.execute_wrapper(readonly): result = audit_plan_approvals(**options) self.assertTrue(queries) encoded = json.dumps(result) self.assertNotIn(self.owner.email, encoded) self.assertNotIn(self.owner.username, encoded) self.assertNotIn(self.plan.name, encoded) self.assertFalse(result["database_modified"]) return result def test_empty_state_is_not_release_approval(self): report = self.audit() self.assertFalse(report["review_required"]) self.assertFalse(report["deployment_approved"]) def test_duplicate_subscriptions_and_pending_applications_are_reported_not_fixed(self): for _ in range(2): Subscription.objects.create(user=self.owner, plan=self.plan) PlanApplication.objects.create(user=self.owner, plan=self.plan) codes = {finding["code"] for finding in self.audit()["findings"]} self.assertEqual(codes, {"multiple_open_subscriptions", "multiple_pending_applications"}) self.assertEqual(Subscription.objects.count(), 2) self.assertEqual(PlanApplication.objects.count(), 2) def test_old_approved_request_is_not_automatically_backfilled(self): app = PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved") report = self.audit() self.assertEqual(report["findings"][0]["code"], "legacy_approved_application_without_link") app.refresh_from_db() self.assertIsNone(app.subscription_id) self.assertFalse(Subscription.objects.exists()) def test_current_plan_change_is_not_a_false_historical_mismatch(self): current = Plan.objects.create(name="Current", slug="current") subscription = Subscription.objects.create(user=self.owner, plan=current, upload_bytes=123) PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved", subscription=subscription) report = self.audit() self.assertFalse(report["findings"]) self.assertTrue(report["schema_rollback_requires_link_backup"]) self.assertEqual(report["schema_rollback_would_drop_link_count"], 1) subscription.refresh_from_db() self.assertEqual(subscription.upload_bytes, 123) def test_cross_user_and_unapproved_links_are_blockers(self): other = get_user_model().objects.create_user(username="other", email="other@example.invalid") subscription = Subscription.objects.create(user=other, plan=self.plan) PlanApplication.objects.create(user=self.owner, plan=self.plan, subscription=subscription) findings = self.audit()["findings"] self.assertEqual({f["code"] for f in findings}, { "subscription_belongs_to_another_user", "unapproved_application_has_subscription_link"}) self.assertTrue(all(f["level"] == "blocker" for f in findings)) def test_ineligible_plans_and_bounded_samples(self): Plan.objects.filter(pk=self.plan.pk).update(active=False) for _ in range(3): PlanApplication.objects.create(user=self.owner, plan=self.plan) findings = {f["code"]: f for f in self.audit(sample_limit=1)["findings"]} finding = findings["pending_plan_no_longer_eligible"] self.assertEqual(finding["count"], 3) self.assertEqual(len(finding["samples"]), 1) self.assertTrue(finding["samples_truncated"]) def test_identity_and_employee_benefit_checks_do_not_flag_unpaid_eligible_requests(self): employee_only = Plan.objects.create(name="Staff", slug="staff", audience="employee") benefit = Plan.objects.create(name="Benefit", slug="benefit", audience="all", employee_benefit=True) other = get_user_model().objects.create_user(username="other-audit", email="other-audit@example.invalid") third = get_user_model().objects.create_user(username="third-audit", email="third-audit@example.invalid") first = PlanApplication.objects.create(user=self.owner, plan=employee_only) second = PlanApplication.objects.create(user=other, plan=benefit) Plan.objects.filter(pk=self.plan.pk).update(price_cny=100) PlanApplication.objects.create(user=third, plan=self.plan, payment_status="unpaid") findings = self.audit()["findings"] self.assertEqual(len(findings), 1) self.assertEqual(findings[0]["code"], "pending_plan_no_longer_eligible") self.assertEqual({row["id"] for row in findings[0]["samples"]}, {first.pk, second.pk}) def test_ended_subscriptions_do_not_count_as_conflicting_open_subscriptions(self): for status in ("cancelled", "expired", "active"): Subscription.objects.create(user=self.owner, plan=self.plan, status=status) self.assertFalse(self.audit()["review_required"]) def test_command_can_fail_after_printing_review_json(self): PlanApplication.objects.create(user=self.owner, plan=self.plan, status="approved") output = io.StringIO() with self.assertRaises(CommandError): call_command("audit_plan_approvals", fail_on_review=True, stdout=output) self.assertTrue(json.loads(output.getvalue())["review_required"]) def test_limit_validation_precedes_queries(self): for limit in (0, 1001): with self.assertNumQueries(0), self.assertRaises(ValueError): audit_plan_approvals(sample_limit=limit) class ApprovalSchemaRehearsalTests(TransactionTestCase): """Only Django's disposable test database; never migrate a deployment here.""" def test_0007_forward_reverse_and_old_schema_audit_preserve_existing_data(self): old_target = [("control", "0007_ai_dispatch")] new_target = [("control", "0008_planapplication_subscription")] executor = MigrationExecutor(connection) latest_targets = executor.loader.graph.leaf_nodes() self.assertTrue(connection.settings_dict["NAME"].startswith(("test_", "file:memory"))) try: executor.migrate(old_target) old_apps = executor.loader.project_state(old_target).apps User = old_apps.get_model("accounts", "User") OldPlan = old_apps.get_model("control", "Plan") OldSub = old_apps.get_model("control", "Subscription") OldApp = old_apps.get_model("control", "PlanApplication") owner = User.objects.create(username="legacy", email="legacy@example.invalid") plan = OldPlan.objects.create(name="Legacy", slug="legacy") sub = OldSub.objects.create(user_id=owner.pk, plan_id=plan.pk, upload_bytes=123, download_bytes=456) app = OldApp.objects.create(user_id=owner.pk, plan_id=plan.pk, status="approved") before = OldSub.objects.values().get(pk=sub.pk) report = audit_plan_approvals() self.assertTrue(report["migration_0008_required"]) self.assertEqual(report["counts"]["applications"], 1) MigrationExecutor(connection).migrate(new_target) self.assertIsNone(PlanApplication.objects.get(pk=app.pk).subscription_id) self.assertEqual(Subscription.objects.values().get(pk=sub.pk), before) # No inferred backfill: association is only set explicitly in fixture. PlanApplication.objects.filter(pk=app.pk).update(subscription_id=sub.pk) self.assertEqual(audit_plan_approvals()["schema_rollback_would_drop_link_count"], 1) MigrationExecutor(connection).migrate(old_target) self.assertEqual(OldSub.objects.values().get(pk=sub.pk), before) self.assertEqual(OldApp.objects.filter(pk=app.pk).count(), 1) MigrationExecutor(connection).migrate(new_target) self.assertIsNone(PlanApplication.objects.get(pk=app.pk).subscription_id) self.assertEqual(Subscription.objects.values().get(pk=sub.pk), before) finally: # A rehearsal of 0008 must not leave later tests running against an old schema. MigrationExecutor(connection).migrate(latest_targets)