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

268 lines
7.5 KiB
Python

#!/usr/bin/env python
"""
Clean test script for email attachment functionality
"""
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',
MEDIA_ROOT='/tmp/test_media',
FILE_UPLOAD_TEMP_DIR='/tmp/test_uploads',
)
# Setup Django
django.setup()
# Now import Django modules
from django.test import TestCase, Client
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.files.base import ContentFile
import io
from unittest.mock import Mock
from recruitment.email_service import send_bulk_email
from recruitment.forms import CandidateEmailForm
from recruitment.models import JobPosting, Candidate
from django.test import RequestFactory
from django.contrib.auth.models import User
# Setup test database
from django.db import connection
from django.core.management import execute_from_command_line
def setup_test_data():
"""Create test data for email attachment testing"""
# Create test user
user = User.objects.create_user(
username='testuser',
email='test@example.com',
first_name='Test',
last_name='User'
)
# Create test job
job = JobPosting.objects.create(
title='Test Job Position',
description='This is a test job for email attachment testing.',
status='ACTIVE',
internal_job_id='TEST-001'
)
# 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'
)
return user, job, candidate
def test_email_service_with_attachments():
"""Test the email service directly with attachments"""
print("Testing email service with attachments...")
# Create test files
test_files = []
# Test 1: Simple text file
text_content = "This is a test attachment content."
text_file = ContentFile(
text_content.encode('utf-8'),
name='test_document.txt'
)
test_files.append(('test_document.txt', text_file, 'text/plain'))
# Test 2: PDF content (simulated)
pdf_content = b'%PDF-1.4\n1 0 obj\n<<\n/Length 100\n>>stream\nxref\nstartxref\n1234\n5678\n/ModDate(D:20250101)\n'
pdf_file = ContentFile(
pdf_content,
name='test_document.pdf'
)
test_files.append(('test_document.pdf', pdf_file, 'application/pdf'))
# Test 3: Image file (simulated PNG header)
image_content = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01'
image_file = ContentFile(
image_content,
name='test_image.png'
)
test_files.append(('test_image.png', image_file, 'image/png'))
try:
# Test email service with attachments
result = send_bulk_email(
subject='Test Email with Attachments',
body='This is a test email with attachments.',
from_email='test@example.com',
recipient_list=['recipient@example.com'],
attachments=test_files
)
print(f"Email service result: {result}")
print("✓ Email service with attachments test passed")
return True
except Exception as e:
print(f"✗ Email service test failed: {e}")
return False
def test_candidate_email_form_with_attachments():
"""Test the CandidateEmailForm with attachments"""
print("\nTesting CandidateEmailForm with attachments...")
user, job, candidate = setup_test_data()
# Create test files for form
text_file = SimpleUploadedFile(
"test.txt",
b"This is test content for form attachment"
)
pdf_file = SimpleUploadedFile(
"test.pdf",
b"%PDF-1.4 test content"
)
form_data = {
'subject': 'Test Subject',
'body': 'Test body content',
'from_email': 'test@example.com',
'recipient_list': 'recipient@example.com',
}
files_data = {
'attachments': [text_file, pdf_file]
}
try:
form = CandidateEmailForm(data=form_data, files=files_data)
if form.is_valid():
print("✓ Form validation passed")
print(f"Form cleaned data: {form.cleaned_data}")
# Test form processing
try:
result = form.save()
print(f"✓ Form save result: {result}")
return True
except Exception as e:
print(f"✗ Form save failed: {e}")
return False
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_view_with_attachments():
"""Test the email view with attachments"""
print("\nTesting email view with attachments...")
user, job, candidate = setup_test_data()
factory = RequestFactory()
# Create a mock request with files
text_file = SimpleUploadedFile(
"test.txt",
b"This is test content for view attachment"
)
request = factory.post(
'/recruitment/send-candidate-email/',
data={
'subject': 'Test Subject',
'body': 'Test body content',
'from_email': 'test@example.com',
'recipient_list': 'recipient@example.com',
},
format='multipart'
)
request.FILES['attachments'] = [text_file]
request.user = user
try:
# Import and test the view
from recruitment.views import send_candidate_email
response = send_candidate_email(request)
print(f"View response status: {response.status_code}")
if response.status_code == 200:
print("✓ Email view test passed")
return True
else:
print(f"✗ Email view test failed with status: {response.status_code}")
return False
except Exception as e:
print(f"✗ Email view test failed: {e}")
return False
def main():
"""Run all email attachment tests"""
print("=" * 60)
print("EMAIL ATTACHMENT 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_with_attachments())
results.append(test_candidate_email_form_with_attachments())
results.append(test_email_view_with_attachments())
# 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 email attachment tests passed!")
return True
else:
print("❌ Some email attachment tests failed!")
return False
if __name__ == '__main__':
success = main()
exit(0 if success else 1)