|
| 1 | +from unittest.mock import patch |
| 2 | + |
| 3 | +import pytest |
| 4 | +import requests |
| 5 | +from django.test import override_settings |
| 6 | + |
| 7 | +from trcustoms.audit_logs.consts import ChangeType |
| 8 | +from trcustoms.audit_logs.tests.factories import AuditLogFactory |
| 9 | +from trcustoms.audit_logs.utils import notify_discord |
| 10 | +from trcustoms.users.tests.factories import UserFactory |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.django_db |
| 14 | +@override_settings(DISCORD_WEBHOOK_URL=None) |
| 15 | +def test_no_webhook(settings): |
| 16 | + audit_log = AuditLogFactory(is_action_required=True) |
| 17 | + with patch("requests.post") as mock_post: |
| 18 | + notify_discord(audit_log) |
| 19 | + mock_post.assert_not_called() |
| 20 | + |
| 21 | + |
| 22 | +@pytest.mark.django_db |
| 23 | +@override_settings(DISCORD_WEBHOOK_URL="http://example.com") |
| 24 | +def test_no_action_required(settings): |
| 25 | + audit_log = AuditLogFactory(is_action_required=False) |
| 26 | + with patch("requests.post") as mock_post: |
| 27 | + notify_discord(audit_log) |
| 28 | + mock_post.assert_not_called() |
| 29 | + |
| 30 | + |
| 31 | +@pytest.mark.django_db |
| 32 | +@override_settings( |
| 33 | + DISCORD_WEBHOOK_URL="http://example.com", |
| 34 | + DISCORD_WEBHOOK_USERNAME="Bot", |
| 35 | + DISCORD_WEBHOOK_AVATAR="https://example.com/av.jpg", |
| 36 | +) |
| 37 | +def test_posts_notification(settings): |
| 38 | + user = UserFactory(username="alice") |
| 39 | + audit_log = AuditLogFactory( |
| 40 | + change_type=ChangeType.UPDATE, |
| 41 | + change_author=user, |
| 42 | + changes=["field1", "field2"], |
| 43 | + is_action_required=True, |
| 44 | + ) |
| 45 | + expected_desc = ( |
| 46 | + f"**{str(audit_log.change_type).title()}** of " |
| 47 | + f"**{audit_log.object_type.model.title()}**" |
| 48 | + f" #{audit_log.object_id} ({audit_log.object_name})" |
| 49 | + f"\n**Author:** {user.username}" |
| 50 | + f"\n**Changes:** {', '.join(audit_log.changes)}" |
| 51 | + ) |
| 52 | + with patch("requests.post") as mock_post: |
| 53 | + notify_discord(audit_log) |
| 54 | + mock_post.assert_called_once_with( |
| 55 | + "http://example.com", |
| 56 | + json={ |
| 57 | + "username": "Bot", |
| 58 | + "avatar_url": "https://example.com/av.jpg", |
| 59 | + "embeds": [{"description": expected_desc}], |
| 60 | + }, |
| 61 | + ) |
| 62 | + |
| 63 | + |
| 64 | +@pytest.mark.django_db |
| 65 | +@override_settings(DISCORD_WEBHOOK_URL="http://example.com") |
| 66 | +def test_exception_swallowed(settings): |
| 67 | + audit_log = AuditLogFactory(is_action_required=True) |
| 68 | + with patch("requests.post", side_effect=requests.RequestException): |
| 69 | + notify_discord(audit_log) |
0 commit comments