kaauh_ats/test_simple_email.py
2025-10-30 19:53:26 +03:00

240 lines
6.9 KiB
Python

#!/usr/bin/env python
"""
Simple test script for basic email functionality without attachments
"""
import os
import sys
import django
from django.conf import settings
# Configure Django settings BEFORE importing any Django modules
if not settings.configured:
settings.configure(
DEBUG=True,
DATABASES={
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
},
USE_TZ=True,
SECRET_KEY='test-secret-key',
INSTALLED_APPS=[
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'recruitment',
],
EMAIL_BACKEND='django.core.mail.backends.console.EmailBackend',
)
# Setup Django
django.setup()
# Now import Django modules
from django.test import TestCase, Client
from django.test import RequestFactory
from django.contrib.auth.models import User
from recruitment.email_service import send_bulk_email
from recruitment.forms import CandidateEmailForm
from recruitment.models import JobPosting, Candidate, Participants
def setup_test_data():
"""Create test data for email testing"""
# Create test user (get or create to avoid duplicates)
user, created = User.objects.get_or_create(
username='testuser',
defaults={
'email': 'test@example.com',
'first_name': 'Test',
'last_name': 'User'
}
)
# Create test job
from datetime import datetime, timedelta
job = JobPosting.objects.create(
title='Test Job Position',
description='This is a test job for email testing.',
status='ACTIVE',
internal_job_id='TEST-001',
application_deadline=datetime.now() + timedelta(days=30)
)
# Create test candidate
candidate = Candidate.objects.create(
first_name='John',
last_name='Doe',
email='john.doe@example.com',
phone='+1234567890',
address='123 Test Street',
job=job,
stage='Interview'
)
# Create test participants
participant1 = Participants.objects.create(
name='Alice Smith',
email='alice@example.com',
phone='+1234567891',
designation='Interviewer'
)
participant2 = Participants.objects.create(
name='Bob Johnson',
email='bob@example.com',
phone='+1234567892',
designation='Hiring Manager'
)
# Add participants to job
job.participants.add(participant1, participant2)
return user, job, candidate, [participant1, participant2]
def test_email_service_basic():
"""Test the email service with basic functionality"""
print("Testing basic email service...")
try:
# Test email service without attachments
result = send_bulk_email(
subject='Test Basic Email',
message='This is a test email without attachments.',
recipient_list=['recipient1@example.com', 'recipient2@example.com']
)
print(f"Email service result: {result}")
print("✓ Basic email service test passed")
return True
except Exception as e:
print(f"✗ Basic email service test failed: {e}")
return False
def test_candidate_email_form_basic():
"""Test the CandidateEmailForm without attachments"""
print("\nTesting CandidateEmailForm without attachments...")
user, job, candidate, participants = setup_test_data()
form_data = {
'subject': 'Test Subject',
'message': 'Test body content',
'recipients': [f'participant_{p.id}' for p in participants],
'include_candidate_info': True,
'include_meeting_details': True,
}
try:
form = CandidateEmailForm(data=form_data, job=job, candidate=candidate)
if form.is_valid():
print("✓ Form validation passed")
print(f"Form cleaned data keys: {list(form.cleaned_data.keys())}")
# Test getting email addresses
email_addresses = form.get_email_addresses()
print(f"Email addresses: {email_addresses}")
# Test getting formatted message
formatted_message = form.get_formatted_message()
print(f"Formatted message length: {len(formatted_message)} characters")
return True
else:
print(f"✗ Form validation failed: {form.errors}")
return False
except Exception as e:
print(f"✗ Form test failed: {e}")
return False
def test_email_sending_workflow():
"""Test the complete email sending workflow"""
print("\nTesting complete email sending workflow...")
user, job, candidate, participants = setup_test_data()
form_data = {
'subject': 'Interview Update: John Doe - Test Job Position',
'message': 'Please find the interview update below.',
'recipients': [f'participant_{p.id}' for p in participants],
'include_candidate_info': True,
'include_meeting_details': True,
}
try:
# Create and validate form
form = CandidateEmailForm(data=form_data, job=job, candidate=candidate)
if not form.is_valid():
print(f"✗ Form validation failed: {form.errors}")
return False
# Get email data
subject = form.cleaned_data['subject']
message = form.get_formatted_message()
recipient_emails = form.get_email_addresses()
print(f"Subject: {subject}")
print(f"Recipients: {recipient_emails}")
print(f"Message preview: {message[:200]}...")
# Send email using service
result = send_bulk_email(
subject=subject,
message=message,
recipient_list=recipient_emails
)
print(f"Email sending result: {result}")
print("✓ Complete email workflow test passed")
return True
except Exception as e:
print(f"✗ Email workflow test failed: {e}")
return False
def main():
"""Run all simple email tests"""
print("=" * 60)
print("SIMPLE EMAIL FUNCTIONALITY TESTS")
print("=" * 60)
# Initialize Django
django.setup()
# Create tables
from django.core.management import execute_from_command_line
execute_from_command_line(['manage.py', 'migrate', '--run-syncdb'])
results = []
# Run tests
results.append(test_email_service_basic())
results.append(test_candidate_email_form_basic())
results.append(test_email_sending_workflow())
# Summary
print("\n" + "=" * 60)
print("TEST SUMMARY")
print("=" * 60)
passed = sum(results)
total = len(results)
print(f"Tests passed: {passed}/{total}")
if passed == total:
print("🎉 All simple email tests passed!")
return True
else:
print("❌ Some simple email tests failed!")
return False
if __name__ == '__main__':
success = main()
exit(0 if success else 1)