Stop a running exchange: - SyncRun gets a Celery task_id and a "stopped" status - The task is bound and passes its id into the run, so the admin can revoke it with app.control.revoke(..., terminate=True) - Admin action "Stop synchronization" reports stopped, already finished, runs without a task id and broker errors separately - A stopped run is never overwritten by the task result Alerts about exchange failures: - NotificationSettings singleton (admin section): on/off, email recipients, Telegram bot token and chat id, per-event flags - notifications.py sends through email and Telegram, best effort: delivery errors are logged and never break the exchange - Fired on catalog apply failure (pull from 1C and inbound push) and on outbox messages that exhausted retries - Admin action "Send test notification" verifies the channels - SMTP settings added to base.py and .env.example so email really works in production; SMS is not implemented (no SMS gateway in the project) Tests: 11 new cases (email/Telegram delivery, flags, outbox dead-letter, stop semantics); the suite is 33 passing.
267 lines
9.5 KiB
Python
267 lines
9.5 KiB
Python
from decimal import Decimal
|
|
from unittest import mock
|
|
|
|
from django.conf import settings
|
|
from django.core import mail
|
|
from django.test import TestCase, override_settings
|
|
from django.utils import timezone
|
|
from rest_framework.test import APIClient
|
|
|
|
from apps.catalog.models import Product
|
|
from apps.orders.models import Order
|
|
|
|
from .models import NotificationSettings, OutboxMessage, SyncLog, SyncRun
|
|
from .services import process_outbox, pull_catalog_from_1c, stop_sync_run
|
|
|
|
|
|
class IntegrationApiTests(TestCase):
|
|
def setUp(self):
|
|
self.client = APIClient()
|
|
self.token = settings.INTEGRATION_API_TOKEN
|
|
|
|
def test_requires_token(self):
|
|
response = self.client.get("/api/v1/integration/1c/health/")
|
|
self.assertEqual(response.status_code, 401)
|
|
|
|
def test_catalog_sync(self):
|
|
payload = {
|
|
"sync_id": "sync-1",
|
|
"categories": [{"external_id": "c1", "name": "Кресла"}],
|
|
"products": [
|
|
{
|
|
"external_id": "p1",
|
|
"sku": "SKU-1",
|
|
"name": "Кресло Эймс",
|
|
"price": "1000.00",
|
|
"stock": 3,
|
|
"category_external_id": "c1",
|
|
"images": [
|
|
{"url": "https://example.com/1.jpg", "is_main": True}
|
|
],
|
|
}
|
|
],
|
|
}
|
|
response = self.client.post(
|
|
"/api/v1/integration/1c/catalog/sync/",
|
|
payload,
|
|
format="json",
|
|
HTTP_X_INTEGRATION_TOKEN=self.token,
|
|
)
|
|
self.assertEqual(response.status_code, 200, response.data)
|
|
self.assertEqual(response.data["stats"]["products_created"], 1)
|
|
|
|
product = Product.objects.get(external_id="p1")
|
|
self.assertEqual(product.price, Decimal("1000.00"))
|
|
self.assertEqual(product.stock, 3)
|
|
self.assertEqual(product.images.count(), 1)
|
|
|
|
def test_order_status_update(self):
|
|
order = Order.objects.create(
|
|
customer_name="Иван",
|
|
phone="+79991234567",
|
|
total=Decimal("1000.00"),
|
|
)
|
|
response = self.client.post(
|
|
f"/api/v1/integration/1c/orders/{order.number}/status/",
|
|
{"status": "Выполнен", "comment": "Выдан клиенту"},
|
|
format="json",
|
|
HTTP_X_INTEGRATION_TOKEN=self.token,
|
|
)
|
|
self.assertEqual(response.status_code, 200, response.data)
|
|
order.refresh_from_db()
|
|
self.assertEqual(order.status, Order.Status.COMPLETED)
|
|
self.assertEqual(order.status_history.count(), 1)
|
|
|
|
def test_unknown_status_is_rejected(self):
|
|
order = Order.objects.create(
|
|
customer_name="Иван",
|
|
phone="+79991234567",
|
|
total=Decimal("1000.00"),
|
|
)
|
|
response = self.client.post(
|
|
f"/api/v1/integration/1c/orders/{order.number}/status/",
|
|
{"status": "Неизвестный статус"},
|
|
format="json",
|
|
HTTP_X_INTEGRATION_TOKEN=self.token,
|
|
)
|
|
self.assertEqual(response.status_code, 400)
|
|
self.assertEqual(response.data["error"]["code"], "unknown_status")
|
|
|
|
|
|
@override_settings(
|
|
EMAIL_BACKEND="django.core.mail.backends.locmem.EmailBackend",
|
|
DEFAULT_FROM_EMAIL="robot@homm.test",
|
|
)
|
|
class ExchangeAlertTests(TestCase):
|
|
def setUp(self):
|
|
self.config = NotificationSettings.load()
|
|
self.config.email_recipients = "admin@homm.test, ops@homm.test"
|
|
self.config.save()
|
|
|
|
def test_sync_failure_sends_email(self):
|
|
with mock.patch(
|
|
"apps.integration.services.OneCClient.fetch_catalog",
|
|
side_effect=RuntimeError("1C недоступна"),
|
|
):
|
|
with self.assertRaises(RuntimeError):
|
|
pull_catalog_from_1c()
|
|
|
|
self.assertEqual(len(mail.outbox), 1)
|
|
message = mail.outbox[0]
|
|
self.assertIn("Сбой обмена с 1С", message.subject)
|
|
self.assertIn("1C недоступна", message.body)
|
|
self.assertEqual(
|
|
sorted(message.to), ["admin@homm.test", "ops@homm.test"]
|
|
)
|
|
|
|
run = SyncRun.objects.latest("started_at")
|
|
self.assertEqual(run.status, SyncRun.Status.FAILED)
|
|
self.assertIn("1C недоступна", run.error)
|
|
|
|
def test_sync_failure_keeps_task_id(self):
|
|
with mock.patch(
|
|
"apps.integration.services.OneCClient.fetch_catalog",
|
|
side_effect=RuntimeError("нет связи"),
|
|
):
|
|
with self.assertRaises(RuntimeError):
|
|
pull_catalog_from_1c(task_id="task-42")
|
|
|
|
run = SyncRun.objects.latest("started_at")
|
|
self.assertEqual(run.task_id, "task-42")
|
|
|
|
def test_disabled_alerts_are_not_sent(self):
|
|
self.config.is_enabled = False
|
|
self.config.save()
|
|
|
|
with mock.patch(
|
|
"apps.integration.services.OneCClient.fetch_catalog",
|
|
side_effect=RuntimeError("1C недоступна"),
|
|
):
|
|
with self.assertRaises(RuntimeError):
|
|
pull_catalog_from_1c()
|
|
|
|
self.assertEqual(len(mail.outbox), 0)
|
|
|
|
def test_catalog_failure_flag_is_respected(self):
|
|
self.config.notify_catalog_failure = False
|
|
self.config.save()
|
|
|
|
with mock.patch(
|
|
"apps.integration.services.OneCClient.fetch_catalog",
|
|
side_effect=RuntimeError("1C недоступна"),
|
|
):
|
|
with self.assertRaises(RuntimeError):
|
|
pull_catalog_from_1c()
|
|
|
|
self.assertEqual(len(mail.outbox), 0)
|
|
|
|
def test_inbound_catalog_error_notifies_admin(self):
|
|
client = APIClient()
|
|
with mock.patch(
|
|
"apps.integration.views.upsert_catalog",
|
|
side_effect=RuntimeError("битый пакет"),
|
|
):
|
|
response = client.post(
|
|
"/api/v1/integration/1c/catalog/sync/",
|
|
{"products": []},
|
|
format="json",
|
|
HTTP_X_INTEGRATION_TOKEN=settings.INTEGRATION_API_TOKEN,
|
|
)
|
|
|
|
self.assertEqual(response.status_code, 400)
|
|
self.assertEqual(len(mail.outbox), 1)
|
|
self.assertIn("битый пакет", mail.outbox[0].body)
|
|
|
|
def test_outbox_dead_letter_notifies_admin(self):
|
|
message = OutboxMessage.objects.create(
|
|
topic="order.created",
|
|
payload={"order_id": 999999},
|
|
attempts=4,
|
|
)
|
|
|
|
process_outbox()
|
|
|
|
message.refresh_from_db()
|
|
self.assertEqual(message.status, OutboxMessage.Status.DEAD)
|
|
self.assertEqual(len(mail.outbox), 1)
|
|
self.assertIn("Заказ не доставлен в 1С", mail.outbox[0].subject)
|
|
|
|
def test_telegram_alert_uses_bot_api(self):
|
|
self.config.email_recipients = ""
|
|
self.config.telegram_bot_token = "123:ABC"
|
|
self.config.telegram_chat_id = "-100500"
|
|
self.config.save()
|
|
|
|
with mock.patch(
|
|
"apps.integration.services.OneCClient.fetch_catalog",
|
|
side_effect=RuntimeError("1C недоступна"),
|
|
):
|
|
with mock.patch(
|
|
"apps.integration.notifications.requests.post"
|
|
) as post:
|
|
post.return_value.raise_for_status.return_value = None
|
|
with self.assertRaises(RuntimeError):
|
|
pull_catalog_from_1c()
|
|
|
|
self.assertEqual(len(mail.outbox), 0)
|
|
post.assert_called_once()
|
|
url = post.call_args.args[0]
|
|
payload = post.call_args.kwargs["json"]
|
|
self.assertIn("123:ABC", url)
|
|
self.assertEqual(payload["chat_id"], "-100500")
|
|
self.assertIn("Сбой обмена", payload["text"])
|
|
|
|
def test_email_list_parses_separators(self):
|
|
self.config.email_recipients = "a@x.ru; b@x.ru,\nc@x.ru"
|
|
self.config.save()
|
|
self.assertEqual(
|
|
self.config.email_list(), ["a@x.ru", "b@x.ru", "c@x.ru"]
|
|
)
|
|
|
|
|
|
class StopSyncRunTests(TestCase):
|
|
def _run(self, **kwargs):
|
|
defaults = {
|
|
"direction": SyncRun.Direction.INBOUND,
|
|
"entity": SyncRun.Entity.CATALOG,
|
|
"status": SyncRun.Status.RUNNING,
|
|
"started_at": timezone.now(),
|
|
}
|
|
defaults.update(kwargs)
|
|
return SyncRun.objects.create(**defaults)
|
|
|
|
def test_stop_revokes_task_and_marks_run(self):
|
|
run = self._run(task_id="task-777")
|
|
|
|
with mock.patch("apps.integration.services.revoke_task") as revoke:
|
|
outcome = stop_sync_run(run)
|
|
|
|
self.assertEqual(outcome, "stopped")
|
|
revoke.assert_called_once_with("task-777")
|
|
|
|
run.refresh_from_db()
|
|
self.assertEqual(run.status, SyncRun.Status.STOPPED)
|
|
self.assertIsNotNone(run.finished_at)
|
|
self.assertEqual(run.logs.count(), 1)
|
|
self.assertEqual(run.logs.first().level, SyncLog.Level.WARNING)
|
|
|
|
def test_stop_skips_finished_run(self):
|
|
run = self._run(status=SyncRun.Status.SUCCESS, task_id="task-1")
|
|
|
|
with mock.patch("apps.integration.services.revoke_task") as revoke:
|
|
self.assertEqual(stop_sync_run(run), "not_running")
|
|
|
|
revoke.assert_not_called()
|
|
run.refresh_from_db()
|
|
self.assertEqual(run.status, SyncRun.Status.SUCCESS)
|
|
|
|
def test_stop_without_task_id_reports_no_task(self):
|
|
run = self._run()
|
|
|
|
with mock.patch("apps.integration.services.revoke_task") as revoke:
|
|
self.assertEqual(stop_sync_run(run), "no_task")
|
|
|
|
revoke.assert_not_called()
|
|
run.refresh_from_db()
|
|
self.assertEqual(run.status, SyncRun.Status.RUNNING)
|