🔍 Code Extractor

function test_email_search

Maturity: 48

Tests the email search functionality of a VendorEmailExtractor instance by searching for emails containing common business terms in the first available mailbox.

File:
/tf/active/vicechatdev/find_email/test_vendor_extractor.py
Lines:
127 - 167
Complexity:
moderate

Purpose

This function serves as a test/validation routine to verify that the email search capability is working correctly. It retrieves the first mailbox from the extractor, searches for emails containing keywords like 'invoice' and 'order' from the last 30 days, and displays the results. It's designed for testing Microsoft Graph API integration and Mail.Read permissions, providing diagnostic output and troubleshooting guidance if errors occur.

Source Code

def test_email_search(extractor):
    """Test searching a mailbox"""
    print("\n" + "="*60)
    print("TESTING EMAIL SEARCH")
    print("="*60)
    
    try:
        # Get first mailbox
        mailboxes = extractor.get_mailboxes(max_mailboxes=1)
        
        if not mailboxes:
            print("⚠️  No mailboxes to test with")
            return True
        
        test_mailbox = mailboxes[0].get('mail')
        print(f"Testing with mailbox: {test_mailbox}")
        
        # Search for emails with common terms
        emails = extractor.search_mailbox(
            user_email=test_mailbox,
            vendor_keywords=["invoice", "order"],  # Common business terms
            max_emails=5,
            days_back=30
        )
        
        print(f"✅ Search completed: Found {len(emails)} emails")
        if emails:
            print("\nSample emails:")
            for email in emails[:3]:
                subject = email.get('subject', 'No subject')
                date = email.get('receivedDateTime', 'No date')
                print(f"  - {subject[:50]}... ({date})")
        
        return True
        
    except Exception as e:
        print(f"❌ Email search failed: {str(e)}")
        print("\nTroubleshooting:")
        print("- This might be a rate limit issue (wait and retry)")
        print("- Verify Mail.Read permission is granted")
        return False

Parameters

Name Type Default Kind
extractor - - positional_or_keyword

Parameter Details

extractor: An instance of VendorEmailExtractor class that has been initialized with proper authentication credentials (tenant_id, client_id, client_secret). This object must have the methods get_mailboxes() and search_mailbox() available. The extractor should be authenticated and ready to make Microsoft Graph API calls.

Return Value

Returns a boolean value: True if the search test completes successfully (regardless of whether emails are found), or False if an exception occurs during the search process. The return value indicates test success/failure rather than search results.

Dependencies

  • vendor_email_extractor
  • vendor_email_config

Required Imports

from vendor_email_extractor import VendorEmailExtractor

Usage Example

from vendor_email_extractor import VendorEmailExtractor
from vendor_email_config import TENANT_ID, CLIENT_ID, CLIENT_SECRET

# Initialize the extractor with credentials
extractor = VendorEmailExtractor(
    tenant_id=TENANT_ID,
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET
)

# Run the email search test
success = test_email_search(extractor)

if success:
    print("Email search test passed")
else:
    print("Email search test failed")

Best Practices

  • Ensure the VendorEmailExtractor instance is properly authenticated before calling this function
  • Verify that Mail.Read permissions are granted in Azure AD before running the test
  • Be aware of Microsoft Graph API rate limits; the function includes troubleshooting guidance for rate limit issues
  • The function searches only the first mailbox returned; ensure test mailboxes are accessible
  • The function uses common business terms ('invoice', 'order') which may not exist in all mailboxes
  • Consider the 30-day lookback period when testing; ensure test mailboxes have recent emails
  • The function prints diagnostic output to stdout; capture or redirect output as needed for automated testing
  • Handle the boolean return value to determine if the test passed or failed
  • This is a test function and should not be used in production code for actual email processing

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_mailbox_access 76.5% similar

    Tests the ability to access and retrieve mailboxes from Microsoft Graph API through a VendorEmailExtractor instance, displaying results and troubleshooting information.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function main_v27 75.5% similar

    Demonstrates example usage of the VendorEmailExtractor class by searching for vendor emails across Office 365 mailboxes and displaying results.

    From: /tf/active/vicechatdev/find_email/vendor_email_extractor.py
  • function run_all_tests 68.7% similar

    Orchestrates a comprehensive test suite for the Vendor Email Extractor system, verifying configuration, authentication, mailbox access, email search, and LLM connectivity.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • function extract_batch 63.0% similar

    Batch processes a list of vendors from an Excel file to extract their email addresses by searching through Microsoft 365 mailboxes using AI-powered email analysis.

    From: /tf/active/vicechatdev/find_email/extract_vendor_batch.py
  • function test_authentication 62.6% similar

    Tests Azure AD authentication for a VendorEmailExtractor instance by attempting to authenticate and providing detailed troubleshooting guidance on failure.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
← Back to Browse