🔍 Code Extractor

class TestEmailHandler

Maturity: 38

A unit test class that validates the functionality of the EmailHandler class, specifically testing email forwarding success and failure scenarios using mocked O365Client dependencies.

File:
/tf/active/vicechatdev/email-forwarder/tests/test_email_handler.py
Lines:
6 - 54
Complexity:
moderate

Purpose

This test class ensures the EmailHandler's forward_email method works correctly by testing both successful email forwarding and error handling when email sending fails. It uses unittest.mock to patch the O365Client.send_email method, allowing isolated testing without actual email transmission. The tests verify that the EmailHandler correctly processes incoming email dictionaries and calls the O365Client with appropriate parameters.

Source Code

class TestEmailHandler(TestCase):

    @patch.object(O365Client, 'send_email')
    def test_forward_email_success(self, mock_send_email):
        # Arrange
        email_handler = EmailHandler()
        mock_send_email.return_value = True
        incoming_email = {
            'from': 'test@example.com',
            'to': 'forwarded@example.com',
            'subject': 'Test Subject',
            'body': 'This is a test email.'
        }

        # Act
        result = email_handler.forward_email(incoming_email)

        # Assert
        self.assertTrue(result)
        mock_send_email.assert_called_once_with(
            to_addresses=['forwarded@example.com'],
            subject='Test Subject',
            body_html='This is a test email.',
            body_text='This is a test email.'
        )

    @patch.object(O365Client, 'send_email')
    def test_forward_email_failure(self, mock_send_email):
        # Arrange
        email_handler = EmailHandler()
        mock_send_email.side_effect = Exception("Email sending failed")
        incoming_email = {
            'from': 'test@example.com',
            'to': 'forwarded@example.com',
            'subject': 'Test Subject',
            'body': 'This is a test email.'
        }

        # Act
        result = email_handler.forward_email(incoming_email)

        # Assert
        self.assertFalse(result)
        mock_send_email.assert_called_once_with(
            to_addresses=['forwarded@example.com'],
            subject='Test Subject',
            body_html='This is a test email.',
            body_text='This is a test email.'
        )

Parameters

Name Type Default Kind
bases TestCase -

Parameter Details

bases: Inherits from unittest.TestCase, which provides the testing framework infrastructure including assertion methods (assertTrue, assertFalse) and test discovery mechanisms

Return Value

As a test class, it doesn't return values directly. Each test method executes assertions that either pass silently or raise AssertionError on failure. The unittest framework collects and reports test results.

Class Interface

Methods

test_forward_email_success(self, mock_send_email)

Purpose: Tests that EmailHandler.forward_email returns True and correctly calls O365Client.send_email when email forwarding succeeds

Parameters:

  • self: The test instance
  • mock_send_email: Mock object injected by @patch decorator that replaces O365Client.send_email

Returns: None (test methods don't return values; they assert conditions)

test_forward_email_failure(self, mock_send_email)

Purpose: Tests that EmailHandler.forward_email returns False and handles exceptions gracefully when O365Client.send_email raises an exception

Parameters:

  • self: The test instance
  • mock_send_email: Mock object injected by @patch decorator that replaces O365Client.send_email and is configured to raise an exception

Returns: None (test methods don't return values; they assert conditions)

Dependencies

  • unittest
  • forwarder.email_handler
  • forwarder.o365_client

Required Imports

from unittest import TestCase
from unittest.mock import patch
from forwarder.email_handler import EmailHandler
from forwarder.o365_client import O365Client

Usage Example

import unittest
from unittest import TestCase
from unittest.mock import patch
from forwarder.email_handler import EmailHandler
from forwarder.o365_client import O365Client

class TestEmailHandler(TestCase):
    @patch.object(O365Client, 'send_email')
    def test_forward_email_success(self, mock_send_email):
        email_handler = EmailHandler()
        mock_send_email.return_value = True
        incoming_email = {
            'from': 'test@example.com',
            'to': 'forwarded@example.com',
            'subject': 'Test Subject',
            'body': 'This is a test email.'
        }
        result = email_handler.forward_email(incoming_email)
        self.assertTrue(result)

if __name__ == '__main__':
    unittest.main()

Best Practices

  • This is a test class and should be run using a test runner (unittest, pytest) rather than instantiated directly
  • Each test method is independent and uses the @patch decorator to mock external dependencies
  • Tests follow the Arrange-Act-Assert pattern for clarity and maintainability
  • Mock objects are configured before the code under test is executed to ensure predictable behavior
  • The class tests both success and failure paths to ensure comprehensive coverage
  • Test methods should be run in isolation; they don't depend on each other's state
  • When adding new tests, follow the naming convention test_<method_name>_<scenario>
  • Always verify both the return value and that mocked methods were called with expected parameters

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class EmailHandler 71.5% similar

    EmailHandler is a comprehensive email processing class that parses incoming email data, extracts content and attachments, enforces rate limits, and forwards emails via Office 365 using the O365Client.

    From: /tf/active/vicechatdev/email-forwarder/src/forwarder/email_handler.py
  • function test_basic_functionality 68.8% similar

    A test function that validates the basic functionality of an EmailHandler instance without sending actual emails, checking initialization, stats retrieval, and rate limiter operation.

    From: /tf/active/vicechatdev/email-forwarder/test_imports.py
  • function test_email_handler 67.2% similar

    A test function that initializes an EmailHandler instance and verifies it can retrieve statistics, printing success or failure messages.

    From: /tf/active/vicechatdev/email-forwarder/test_service.py
  • function test_send_email 66.6% similar

    Interactive test function that prompts the user to send a test email through the O365Client to verify email sending functionality.

    From: /tf/active/vicechatdev/email-forwarder/test_service.py
  • class TestSmtpServer 64.6% similar

    A test class for validating the functionality of the SmtpServer class, including server startup, email handling, email forwarding, and error handling for invalid inputs.

    From: /tf/active/vicechatdev/email-forwarder/tests/test_smtp_server.py
← Back to Browse