Buckets:

download
raw
31.8 kB
"""
Comprehensive Unit Tests for Notification Model
===============================================
This module provides 90-100% code coverage tests for the notification_model.py file.
All enums, dataclasses, methods, and properties are thoroughly tested.
Author: Zen-AI-Pentest Team
Version: 1.0.0
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Any, Dict, List
import pytest
from models.notification_model import (
Notification,
NotificationAttachment,
NotificationChannel,
NotificationStatus,
NotificationType,
)
# =============================================================================
# Fixtures
# =============================================================================
@pytest.fixture
def valid_notification() -> Notification:
"""Fixture for a valid Notification instance."""
return Notification(
id="notif-001",
title="Test Notification",
message="This is a test message",
notification_type=NotificationType.INFO,
channels=[NotificationChannel.EMAIL, NotificationChannel.SLACK],
recipient="user@example.com",
)
@pytest.fixture
def notification_with_attachment() -> Notification:
"""Fixture for a notification with attachment."""
attachment = NotificationAttachment(
filename="test.pdf",
content=b"test content",
mime_type="application/pdf",
)
return Notification(
id="notif-002",
title="Notification with Attachment",
message="This notification has an attachment",
notification_type=NotificationType.WARNING,
channels=[NotificationChannel.EMAIL],
attachments=[attachment],
metadata={"scan_id": "scan-001", "priority": "high"},
)
@pytest.fixture
def failed_notification() -> Notification:
"""Fixture for a failed notification."""
return Notification(
id="notif-003",
title="Failed Notification",
message="This notification failed",
notification_type=NotificationType.ERROR,
channels=[NotificationChannel.WEBHOOK],
status=NotificationStatus.FAILED,
retry_count=2,
error_message="Connection timeout",
)
# =============================================================================
# Enum Tests - NotificationType
# =============================================================================
class TestNotificationType:
"""Tests for NotificationType enum."""
def test_all_enum_values_exist(self) -> None:
"""Test that all NotificationType enum values are defined."""
expected_values = {"INFO", "WARNING", "ERROR", "CRITICAL", "SUCCESS"}
actual_values = {e.name for e in NotificationType}
assert actual_values == expected_values
def test_enum_values_are_strings(self) -> None:
"""Test that enum values are strings."""
assert isinstance(NotificationType.INFO.value, str)
assert NotificationType.INFO.value == "info"
assert NotificationType.WARNING.value == "warning"
assert NotificationType.ERROR.value == "error"
assert NotificationType.CRITICAL.value == "critical"
assert NotificationType.SUCCESS.value == "success"
def test_enum_comparison(self) -> None:
"""Test enum value comparison."""
assert NotificationType.INFO == NotificationType.INFO
assert NotificationType.INFO != NotificationType.WARNING
assert NotificationType.CRITICAL.value == "critical"
def test_enum_membership(self) -> None:
"""Test enum membership checking."""
assert NotificationType.ERROR in NotificationType
assert NotificationType("info") == NotificationType.INFO
# =============================================================================
# Enum Tests - NotificationChannel
# =============================================================================
class TestNotificationChannel:
"""Tests for NotificationChannel enum."""
def test_all_enum_values_exist(self) -> None:
"""Test that all NotificationChannel enum values are defined."""
expected_values = {
"EMAIL",
"SLACK",
"DISCORD",
"TELEGRAM",
"WEBHOOK",
"SMS",
"IN_APP",
}
actual_values = {e.name for e in NotificationChannel}
assert actual_values == expected_values
def test_enum_values_are_strings(self) -> None:
"""Test that enum values are strings."""
assert NotificationChannel.EMAIL.value == "email"
assert NotificationChannel.SLACK.value == "slack"
assert NotificationChannel.DISCORD.value == "discord"
assert NotificationChannel.TELEGRAM.value == "telegram"
assert NotificationChannel.WEBHOOK.value == "webhook"
assert NotificationChannel.SMS.value == "sms"
assert NotificationChannel.IN_APP.value == "in_app"
def test_all_channels_unique(self) -> None:
"""Test that all channel values are unique."""
values = [ch.value for ch in NotificationChannel]
assert len(values) == len(set(values))
# =============================================================================
# Enum Tests - NotificationStatus
# =============================================================================
class TestNotificationStatus:
"""Tests for NotificationStatus enum."""
def test_all_enum_values_exist(self) -> None:
"""Test that all NotificationStatus enum values are defined."""
expected_values = {
"PENDING",
"QUEUED",
"SENDING",
"SENT",
"DELIVERED",
"FAILED",
"RETRYING",
"CANCELLED",
}
actual_values = {e.name for e in NotificationStatus}
assert actual_values == expected_values
def test_enum_values_are_strings(self) -> None:
"""Test that enum values are strings."""
assert NotificationStatus.PENDING.value == "pending"
assert NotificationStatus.QUEUED.value == "queued"
assert NotificationStatus.SENDING.value == "sending"
assert NotificationStatus.SENT.value == "sent"
assert NotificationStatus.DELIVERED.value == "delivered"
assert NotificationStatus.FAILED.value == "failed"
assert NotificationStatus.RETRYING.value == "retrying"
assert NotificationStatus.CANCELLED.value == "cancelled"
def test_status_flow_order(self) -> None:
"""Test typical notification status flow."""
flow = [
NotificationStatus.PENDING,
NotificationStatus.QUEUED,
NotificationStatus.SENDING,
NotificationStatus.SENT,
NotificationStatus.DELIVERED,
]
for status in flow:
assert isinstance(status.value, str)
# =============================================================================
# NotificationAttachment Tests
# =============================================================================
class TestNotificationAttachment:
"""Tests for NotificationAttachment dataclass."""
def test_valid_attachment(self) -> None:
"""Test creating a valid attachment."""
attachment = NotificationAttachment(
filename="report.pdf",
content=b"pdf content",
mime_type="application/pdf",
)
assert attachment.filename == "report.pdf"
assert attachment.content == b"pdf content"
assert attachment.mime_type == "application/pdf"
def test_default_mime_type(self) -> None:
"""Test default MIME type for attachment."""
attachment = NotificationAttachment(
filename="data.bin",
content=b"binary data",
)
assert attachment.mime_type == "application/octet-stream"
def test_empty_content(self) -> None:
"""Test attachment with empty content."""
attachment = NotificationAttachment(
filename="empty.txt",
content=b"",
mime_type="text/plain",
)
assert attachment.content == b""
# =============================================================================
# Notification Tests - Initialization
# =============================================================================
class TestNotificationInitialization:
"""Tests for Notification initialization."""
def test_valid_notification(self) -> None:
"""Test creating a valid notification."""
notification = Notification(
id="notif-001",
title="Test Title",
message="Test message content",
)
assert notification.id == "notif-001"
assert notification.title == "Test Title"
assert notification.message == "Test message content"
assert notification.notification_type == NotificationType.INFO
assert notification.channels == []
assert notification.status == NotificationStatus.PENDING
def test_notification_with_all_fields(self, valid_notification) -> None:
"""Test notification with all fields populated."""
assert valid_notification.id == "notif-001"
assert valid_notification.title == "Test Notification"
assert valid_notification.message == "This is a test message"
assert valid_notification.notification_type == NotificationType.INFO
assert len(valid_notification.channels) == 2
assert NotificationChannel.EMAIL in valid_notification.channels
assert NotificationChannel.SLACK in valid_notification.channels
assert valid_notification.recipient == "user@example.com"
def test_notification_with_metadata(self, notification_with_attachment) -> None:
"""Test notification with metadata."""
assert notification_with_attachment.metadata == {
"scan_id": "scan-001",
"priority": "high",
}
def test_notification_with_attachments(self, notification_with_attachment) -> None:
"""Test notification with attachments."""
assert len(notification_with_attachment.attachments) == 1
attachment = notification_with_attachment.attachments[0]
assert attachment.filename == "test.pdf"
assert attachment.content == b"test content"
def test_empty_title_validation(self) -> None:
"""Test that empty title raises ValueError."""
with pytest.raises(ValueError, match="Title cannot be empty"):
Notification(
id="notif-001",
title="",
message="Valid message",
)
def test_empty_message_validation(self) -> None:
"""Test that empty message raises ValueError."""
with pytest.raises(ValueError, match="Message cannot be empty"):
Notification(
id="notif-001",
title="Valid title",
message="",
)
def test_default_timestamps(self) -> None:
"""Test that created_at is set by default."""
before = datetime.now(timezone.utc)
notification = Notification(
id="notif-001",
title="Test",
message="Message",
)
after = datetime.now(timezone.utc)
assert before <= notification.created_at <= after
assert notification.sent_at is None
assert notification.delivered_at is None
def test_default_retry_settings(self) -> None:
"""Test default retry settings."""
notification = Notification(
id="notif-001",
title="Test",
message="Message",
)
assert notification.retry_count == 0
assert notification.max_retries == 3
# =============================================================================
# Notification Tests - Status Methods
# =============================================================================
class TestNotificationStatusMethods:
"""Tests for notification status change methods."""
def test_mark_as_sent(self, valid_notification) -> None:
"""Test marking notification as sent."""
assert valid_notification.sent_at is None
assert valid_notification.status == NotificationStatus.PENDING
valid_notification.mark_as_sent()
assert valid_notification.status == NotificationStatus.SENT
assert valid_notification.sent_at is not None
assert isinstance(valid_notification.sent_at, datetime)
def test_mark_as_delivered(self, valid_notification) -> None:
"""Test marking notification as delivered."""
assert valid_notification.delivered_at is None
valid_notification.mark_as_delivered()
assert valid_notification.status == NotificationStatus.DELIVERED
assert valid_notification.delivered_at is not None
assert isinstance(valid_notification.delivered_at, datetime)
def test_mark_as_failed(self, valid_notification) -> None:
"""Test marking notification as failed."""
error_msg = "Connection refused"
valid_notification.mark_as_failed(error_msg)
assert valid_notification.status == NotificationStatus.FAILED
assert valid_notification.error_message == error_msg
def test_mark_as_failed_with_empty_error(self, valid_notification) -> None:
"""Test marking notification as failed with empty error."""
valid_notification.mark_as_failed("")
assert valid_notification.status == NotificationStatus.FAILED
assert valid_notification.error_message == ""
def test_status_transitions_sequence(self, valid_notification) -> None:
"""Test a complete status transition sequence."""
# Initial state
assert valid_notification.status == NotificationStatus.PENDING
assert not valid_notification.is_delivered()
assert not valid_notification.is_failed()
# Mark as sent
valid_notification.mark_as_sent()
assert valid_notification.status == NotificationStatus.SENT
# Mark as delivered
valid_notification.mark_as_delivered()
assert valid_notification.status == NotificationStatus.DELIVERED
assert valid_notification.is_delivered()
assert not valid_notification.is_failed()
# =============================================================================
# Notification Tests - Retry Methods
# =============================================================================
class TestNotificationRetryMethods:
"""Tests for notification retry functionality."""
def test_increment_retry_first_attempt(self, valid_notification) -> None:
"""Test first retry increment."""
assert valid_notification.retry_count == 0
assert valid_notification.status == NotificationStatus.PENDING
can_retry = valid_notification.increment_retry()
assert can_retry is True
assert valid_notification.retry_count == 1
assert valid_notification.status == NotificationStatus.RETRYING
def test_increment_retry_until_max(self, valid_notification) -> None:
"""Test retry increments until max reached."""
valid_notification.status = NotificationStatus.FAILED
# First retry (count: 0 -> 1, 1 < 3 = True)
assert valid_notification.increment_retry() is True
assert valid_notification.retry_count == 1
# Second retry (count: 1 -> 2, 2 < 3 = True)
valid_notification.status = NotificationStatus.FAILED
assert valid_notification.increment_retry() is True
assert valid_notification.retry_count == 2
# Third retry (count: 2 -> 3, 3 < 3 = False - max reached)
valid_notification.status = NotificationStatus.FAILED
assert valid_notification.increment_retry() is False
assert valid_notification.retry_count == 3
def test_increment_retry_at_max(self, valid_notification) -> None:
"""Test retry when max retries reached."""
valid_notification.retry_count = 3 # max_retries is 3
valid_notification.status = NotificationStatus.FAILED
can_retry = valid_notification.increment_retry()
assert can_retry is False
assert valid_notification.retry_count == 4
# Status remains RETRYING from increment_retry
def test_can_retry_when_failed(self, failed_notification) -> None:
"""Test can_retry when notification failed."""
assert failed_notification.can_retry() is True
assert failed_notification.retry_count < failed_notification.max_retries
def test_can_retry_when_max_reached(self, failed_notification) -> None:
"""Test can_retry when max retries reached."""
failed_notification.retry_count = 3 # max_retries is 3
assert failed_notification.can_retry() is False
def test_can_retry_when_not_failed(self, valid_notification) -> None:
"""Test can_retry when notification is not in failed state."""
valid_notification.status = NotificationStatus.SENT
assert valid_notification.can_retry() is False
def test_can_retry_when_retrying(self) -> None:
"""Test can_retry when notification is retrying."""
notification = Notification(
id="notif-001",
title="Test",
message="Message",
status=NotificationStatus.RETRYING,
retry_count=1,
)
assert notification.can_retry() is True
# =============================================================================
# Notification Tests - Query Methods
# =============================================================================
class TestNotificationQueryMethods:
"""Tests for notification query methods."""
def test_is_delivered_true(self, valid_notification) -> None:
"""Test is_delivered returns True when delivered."""
valid_notification.status = NotificationStatus.DELIVERED
assert valid_notification.is_delivered() is True
def test_is_delivered_false(self, valid_notification) -> None:
"""Test is_delivered returns False when not delivered."""
valid_notification.status = NotificationStatus.SENT
assert valid_notification.is_delivered() is False
def test_is_failed_true(self, failed_notification) -> None:
"""Test is_failed returns True when failed."""
assert failed_notification.is_failed() is True
def test_is_failed_false(self, valid_notification) -> None:
"""Test is_failed returns False when not failed."""
valid_notification.status = NotificationStatus.SENT
assert valid_notification.is_failed() is False
# =============================================================================
# Notification Tests - Serialization
# =============================================================================
class TestNotificationSerialization:
"""Tests for notification serialization."""
def test_to_dict_basic(self, valid_notification) -> None:
"""Test basic dictionary conversion."""
data = valid_notification.to_dict()
assert isinstance(data, dict)
assert data["id"] == "notif-001"
assert data["title"] == "Test Notification"
assert data["message"] == "This is a test message"
assert data["type"] == "info"
assert data["recipient"] == "user@example.com"
def test_to_dict_channels(self, valid_notification) -> None:
"""Test dictionary conversion includes channels."""
data = valid_notification.to_dict()
assert "channels" in data
assert "email" in data["channels"]
assert "slack" in data["channels"]
def test_to_dict_status(self, valid_notification) -> None:
"""Test dictionary conversion includes status."""
data = valid_notification.to_dict()
assert data["status"] == "pending"
def test_to_dict_timestamps(self, valid_notification) -> None:
"""Test dictionary conversion includes timestamps."""
valid_notification.mark_as_sent()
valid_notification.mark_as_delivered()
data = valid_notification.to_dict()
assert data["sent_at"] is not None
assert data["delivered_at"] is not None
assert isinstance(data["sent_at"], str)
assert isinstance(data["delivered_at"], str)
def test_to_dict_none_timestamps(self, valid_notification) -> None:
"""Test dictionary conversion with None timestamps."""
data = valid_notification.to_dict()
assert data["sent_at"] is None
assert data["delivered_at"] is None
def test_to_dict_metadata(self, notification_with_attachment) -> None:
"""Test dictionary conversion includes metadata."""
data = notification_with_attachment.to_dict()
assert data["metadata"] == {"scan_id": "scan-001", "priority": "high"}
def test_to_dict_retry_info(self, failed_notification) -> None:
"""Test dictionary conversion includes retry information."""
data = failed_notification.to_dict()
assert data["retry_count"] == 2
assert data["max_retries"] == 3
assert data["error_message"] == "Connection timeout"
def test_to_dict_all_notification_types(self) -> None:
"""Test dictionary conversion for all notification types."""
for notif_type in NotificationType:
notification = Notification(
id="test",
title="Test",
message="Message",
notification_type=notif_type,
)
data = notification.to_dict()
assert data["type"] == notif_type.value
def test_to_dict_all_statuses(self) -> None:
"""Test dictionary conversion for all statuses."""
for status in NotificationStatus:
notification = Notification(
id="test",
title="Test",
message="Message",
status=status,
)
data = notification.to_dict()
assert data["status"] == status.value
# =============================================================================
# Notification Tests - Edge Cases
# =============================================================================
class TestNotificationEdgeCases:
"""Tests for edge cases and boundary conditions."""
def test_very_long_title(self) -> None:
"""Test notification with very long title."""
long_title = "A" * 1000
notification = Notification(
id="test",
title=long_title,
message="Message",
)
assert notification.title == long_title
def test_very_long_message(self) -> None:
"""Test notification with very long message."""
long_message = "B" * 10000
notification = Notification(
id="test",
title="Title",
message=long_message,
)
assert notification.message == long_message
def test_special_characters_in_title(self) -> None:
"""Test notification with special characters in title."""
special_title = "Test <script>alert('xss')</script> & More"
notification = Notification(
id="test",
title=special_title,
message="Message",
)
assert notification.title == special_title
def test_unicode_content(self) -> None:
"""Test notification with unicode content."""
notification = Notification(
id="test-日本語",
title="Hello 世界 🌍",
message="Café résumé naïve",
)
assert notification.title == "Hello 世界 🌍"
assert notification.message == "Café résumé naïve"
def test_multiple_attachments(self) -> None:
"""Test notification with multiple attachments."""
attachments = [NotificationAttachment(f"file{i}.txt", f"content{i}".encode()) for i in range(5)]
notification = Notification(
id="test",
title="Title",
message="Message",
attachments=attachments,
)
assert len(notification.attachments) == 5
def test_all_channels(self) -> None:
"""Test notification with all channels."""
notification = Notification(
id="test",
title="Title",
message="Message",
channels=list(NotificationChannel),
)
assert len(notification.channels) == len(NotificationChannel)
def test_empty_metadata(self) -> None:
"""Test notification with empty metadata."""
notification = Notification(
id="test",
title="Title",
message="Message",
metadata={},
)
data = notification.to_dict()
assert data["metadata"] == {}
def test_nested_metadata(self) -> None:
"""Test notification with nested metadata."""
nested_metadata = {
"level1": {"level2": {"level3": ["value1", "value2"]}},
"numbers": [1, 2, 3],
}
notification = Notification(
id="test",
title="Title",
message="Message",
metadata=nested_metadata,
)
data = notification.to_dict()
assert data["metadata"] == nested_metadata
def test_custom_max_retries(self) -> None:
"""Test notification with custom max_retries."""
notification = Notification(
id="test",
title="Title",
message="Message",
max_retries=5,
)
assert notification.max_retries == 5
assert notification.retry_count == 0
def test_multiple_status_changes(self, valid_notification) -> None:
"""Test multiple status changes."""
# PENDING -> SENT -> DELIVERED
valid_notification.mark_as_sent()
assert valid_notification.status == NotificationStatus.SENT
valid_notification.mark_as_delivered()
assert valid_notification.status == NotificationStatus.DELIVERED
# Can still mark as failed after delivery (edge case)
valid_notification.mark_as_failed("Late failure")
assert valid_notification.status == NotificationStatus.FAILED
def test_sent_at_preserved_on_redelivery(self, valid_notification) -> None:
"""Test that sent_at is not reset on redelivery."""
valid_notification.mark_as_sent()
first_sent_at = valid_notification.sent_at
# Simulate some delay
import time
time.sleep(0.01)
valid_notification.mark_as_delivered()
# sent_at should remain the same
assert valid_notification.sent_at == first_sent_at
# =============================================================================
# Integration Tests
# =============================================================================
class TestNotificationIntegration:
"""Integration tests for notification workflows."""
def test_full_notification_lifecycle(self) -> None:
"""Test a complete notification lifecycle."""
# Create notification
notification = Notification(
id="lifecycle-test",
title="Lifecycle Test",
message="Testing full lifecycle",
notification_type=NotificationType.INFO,
channels=[NotificationChannel.EMAIL],
recipient="test@example.com",
metadata={"test": True},
)
# Initial state
assert notification.status == NotificationStatus.PENDING
assert not notification.is_delivered()
assert not notification.is_failed()
# Send
notification.mark_as_sent()
assert notification.status == NotificationStatus.SENT
assert notification.sent_at is not None
# Deliver
notification.mark_as_delivered()
assert notification.status == NotificationStatus.DELIVERED
assert notification.is_delivered()
assert notification.delivered_at is not None
# Serialize
data = notification.to_dict()
assert data["id"] == "lifecycle-test"
assert data["status"] == "delivered"
assert data["type"] == "info"
def test_failed_notification_with_retries(self) -> None:
"""Test a failed notification that exhausts retries."""
notification = Notification(
id="retry-test",
title="Retry Test",
message="Testing retry logic",
max_retries=2,
)
# First failure
notification.mark_as_failed("Error 1")
assert notification.is_failed()
assert notification.can_retry()
# First retry
notification.increment_retry()
assert notification.retry_count == 1
notification.mark_as_failed("Error 2")
assert notification.can_retry()
# Second retry
notification.increment_retry()
assert notification.retry_count == 2
notification.mark_as_failed("Error 3")
assert not notification.can_retry() # Max retries reached
# One more increment should return False
can_retry = notification.increment_retry()
assert not can_retry
assert notification.retry_count == 3
def test_notification_with_all_channel_types(self) -> None:
"""Test creating notifications for each channel type."""
for channel in NotificationChannel:
notification = Notification(
id=f"test-{channel.value}",
title=f"Test {channel.name}",
message=f"Message for {channel.value}",
channels=[channel],
notification_type=NotificationType.INFO,
)
assert len(notification.channels) == 1
assert notification.channels[0] == channel
def test_notification_type_variations(self) -> None:
"""Test creating notifications with all notification types."""
for notif_type in NotificationType:
notification = Notification(
id="test",
title="Test",
message="Message",
notification_type=notif_type,
)
data = notification.to_dict()
assert data["type"] == notif_type.value
def test_bulk_notification_creation(self) -> None:
"""Test creating multiple notifications efficiently."""
notifications: List[Notification] = []
for i in range(100):
notification = Notification(
id=f"bulk-{i}",
title=f"Bulk Notification {i}",
message=f"Message {i}",
notification_type=(NotificationType.INFO if i % 2 == 0 else NotificationType.WARNING),
channels=[NotificationChannel.IN_APP],
)
notifications.append(notification)
assert len(notifications) == 100
assert notifications[0].title == "Bulk Notification 0"
assert notifications[99].title == "Bulk Notification 99"
def test_notification_equality_through_serialization(self) -> None:
"""Test that identical notifications serialize to equivalent dicts."""
notification1 = Notification(
id="test",
title="Title",
message="Message",
created_at=datetime(2024, 1, 1, 12, 0, 0),
)
notification2 = Notification(
id="test",
title="Title",
message="Message",
created_at=datetime(2024, 1, 1, 12, 0, 0),
)
# Different objects
assert notification1 is not notification2
# But same content when serialized
assert notification1.to_dict() == notification2.to_dict()

Xet Storage Details

Size:
31.8 kB
·
Xet hash:
dde7a552d09b2972bea7e8f7625d191c2b366f30e185433f95140199b0bef037

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.