from decimal import Decimal from io import StringIO from unittest import mock import requests from django.conf import settings from django.contrib import admin from django.core import mail from django.core.management import call_command from django.core.management.base import CommandError from django.test import RequestFactory, 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 .admin import NotificationSettingsAdmin from .models import NotificationSettings, OutboxMessage, SyncLog, SyncRun from .services import process_outbox, pull_catalog_from_1c, stop_sync_run from .telegram import TelegramError, get_me, recent_chats, send_message 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.telegram.requests.post" ) as post: response = post.return_value response.status_code = 200 response.json.return_value = {"ok": True, "result": {"message_id": 1}} 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) class TelegramClientTests(TestCase): def _response(self, status=200, payload=None): response = mock.Mock() response.status_code = status response.json.return_value = payload or {"ok": True, "result": {}} return response @mock.patch("apps.integration.telegram.requests.post") def test_send_message_posts_to_bot_api(self, post): post.return_value = self._response( payload={"ok": True, "result": {"message_id": 7}} ) send_message("123:ABC", "-100500", "Привет") self.assertEqual( post.call_args.args[0], "https://api.telegram.org/bot123:ABC/sendMessage", ) payload = post.call_args.kwargs["json"] self.assertEqual(payload["chat_id"], "-100500") self.assertEqual(payload["text"], "Привет") self.assertTrue(payload["disable_web_page_preview"]) @mock.patch("apps.integration.telegram.requests.post") def test_long_message_is_truncated(self, post): post.return_value = self._response() send_message("123:ABC", "1", "а" * 5000) text = post.call_args.kwargs["json"]["text"] self.assertEqual(len(text), 4096) self.assertTrue(text.endswith("(сообщение обрезано)")) @mock.patch("apps.integration.telegram.requests.post") def test_api_error_is_reported_with_description(self, post): post.return_value = self._response( status=400, payload={"ok": False, "description": "Bad Request: chat not found"}, ) with self.assertRaises(TelegramError) as ctx: send_message("123:ABC", "1", "текст") self.assertIn("chat not found", str(ctx.exception)) @mock.patch("apps.integration.telegram.requests.post") def test_network_error_is_wrapped(self, post): post.side_effect = requests.RequestException("нет сети") with self.assertRaises(TelegramError) as ctx: get_me("123:ABC") self.assertIn("Telegram недоступен", str(ctx.exception)) def test_missing_token_is_rejected(self): with self.assertRaises(TelegramError): send_message("", "1", "текст") @mock.patch("apps.integration.telegram.requests.post") def test_recent_chats_dedupes_and_names_private_chats(self, post): post.return_value = self._response( payload={ "ok": True, "result": [ { "message": { "chat": { "id": 111, "type": "private", "first_name": "Иван", "last_name": "Петров", } } }, {"message": {"chat": {"id": 111, "type": "private"}}}, { "message": { "chat": {"id": -100500, "type": "channel", "title": "HOMM"} } }, ], } ) chats = recent_chats("123:ABC") self.assertEqual([chat["id"] for chat in chats], ["111", "-100500"]) self.assertEqual(chats[0]["title"], "Иван Петров") self.assertEqual(chats[1]["title"], "HOMM") class TelegramCommandTests(TestCase): def setUp(self): self.config = NotificationSettings.load() self.config.telegram_bot_token = "123:ABC" self.config.telegram_chat_id = "-100500" self.config.save() @mock.patch("apps.integration.management.commands.telegram_check.recent_chats") @mock.patch("apps.integration.management.commands.telegram_check.send_message") @mock.patch("apps.integration.management.commands.telegram_check.get_me") def test_check_sends_test_message(self, get_me, send_message_mock, chats): get_me.return_value = {"id": 1, "username": "homm_bot", "first_name": "HOMM"} chats.return_value = [] out = StringIO() call_command("telegram_check", stdout=out) text = out.getvalue() self.assertIn("Бот найден: @homm_bot", text) self.assertIn("Тестовое сообщение отправлено", text) send_message_mock.assert_called_once() self.assertEqual(send_message_mock.call_args.args[1], "-100500") def test_check_without_token_fails(self): self.config.telegram_bot_token = "" self.config.save() with self.assertRaises(CommandError): call_command("telegram_check", stdout=StringIO()) @mock.patch("apps.integration.management.commands.telegram_check.send_message") @mock.patch("apps.integration.management.commands.telegram_check.get_me") def test_check_with_telegram_error_fails_clearly(self, get_me, send): get_me.return_value = {"id": 1, "username": "homm_bot"} send.side_effect = TelegramError("Telegram API: chat not found") with self.assertRaises(CommandError) as ctx: call_command("telegram_check", stdout=StringIO()) self.assertIn("chat not found", str(ctx.exception)) @mock.patch("apps.integration.management.commands.telegram_chats.recent_chats") def test_chats_apply_saves_single_chat(self, chats): chats.return_value = [ {"id": "-100777", "type": "group", "title": "HOMM ops", "username": ""} ] call_command("telegram_chats", "--apply", stdout=StringIO()) self.config.refresh_from_db() self.assertEqual(self.config.telegram_chat_id, "-100777") @mock.patch("apps.integration.management.commands.telegram_chats.recent_chats") def test_chats_apply_requires_single_chat(self, chats): chats.return_value = [ {"id": "1", "type": "private", "title": "Иван", "username": ""}, {"id": "2", "type": "private", "title": "Пётр", "username": ""}, ] with self.assertRaises(CommandError): call_command("telegram_chats", "--apply", stdout=StringIO()) class TelegramAdminActionTests(TestCase): def test_detect_chat_id_saves_single_chat(self): config = NotificationSettings.load() config.telegram_bot_token = "123:ABC" config.save() model_admin = NotificationSettingsAdmin(NotificationSettings, admin.site) request = RequestFactory().get("/admin/integration/notificationsettings/") with mock.patch.object(model_admin, "message_user") as message_user: with mock.patch( "apps.integration.admin.recent_chats", return_value=[ {"id": "-100900", "title": "HOMM alerts", "type": "group", "username": ""} ], ): model_admin.detect_chat_id(request, NotificationSettings.objects.all()) config.refresh_from_db() self.assertEqual(config.telegram_chat_id, "-100900") message_user.assert_called_once() self.assertIn("chat_id сохранён", message_user.call_args.args[1])