| 1 |
import sys, time, os |
|---|
| 2 |
from django.conf import settings |
|---|
| 3 |
from django.db import connection |
|---|
| 4 |
from django.core import mail |
|---|
| 5 |
from django.test import signals |
|---|
| 6 |
from django.template import Template |
|---|
| 7 |
from django.utils.translation import deactivate |
|---|
| 8 |
|
|---|
| 9 |
def instrumented_test_render(self, context): |
|---|
| 10 |
""" |
|---|
| 11 |
An instrumented Template render method, providing a signal |
|---|
| 12 |
that can be intercepted by the test system Client |
|---|
| 13 |
""" |
|---|
| 14 |
signals.template_rendered.send(sender=self, template=self, context=context) |
|---|
| 15 |
return self.nodelist.render(context) |
|---|
| 16 |
|
|---|
| 17 |
class TestSMTPConnection(object): |
|---|
| 18 |
"""A substitute SMTP connection for use during test sessions. |
|---|
| 19 |
The test connection stores email messages in a dummy outbox, |
|---|
| 20 |
rather than sending them out on the wire. |
|---|
| 21 |
|
|---|
| 22 |
""" |
|---|
| 23 |
def __init__(*args, **kwargs): |
|---|
| 24 |
pass |
|---|
| 25 |
def open(self): |
|---|
| 26 |
"Mock the SMTPConnection open() interface" |
|---|
| 27 |
pass |
|---|
| 28 |
def close(self): |
|---|
| 29 |
"Mock the SMTPConnection close() interface" |
|---|
| 30 |
pass |
|---|
| 31 |
def send_messages(self, messages): |
|---|
| 32 |
"Redirect messages to the dummy outbox" |
|---|
| 33 |
mail.outbox.extend(messages) |
|---|
| 34 |
return len(messages) |
|---|
| 35 |
|
|---|
| 36 |
def setup_test_environment(): |
|---|
| 37 |
"""Perform any global pre-test setup. This involves: |
|---|
| 38 |
|
|---|
| 39 |
- Installing the instrumented test renderer |
|---|
| 40 |
- Diverting the email sending functions to a test buffer |
|---|
| 41 |
- Setting the active locale to match the LANGUAGE_CODE setting. |
|---|
| 42 |
""" |
|---|
| 43 |
Template.original_render = Template.render |
|---|
| 44 |
Template.render = instrumented_test_render |
|---|
| 45 |
|
|---|
| 46 |
mail.original_SMTPConnection = mail.SMTPConnection |
|---|
| 47 |
mail.SMTPConnection = TestSMTPConnection |
|---|
| 48 |
|
|---|
| 49 |
mail.outbox = [] |
|---|
| 50 |
|
|---|
| 51 |
deactivate() |
|---|
| 52 |
|
|---|
| 53 |
def teardown_test_environment(): |
|---|
| 54 |
"""Perform any global post-test teardown. This involves: |
|---|
| 55 |
|
|---|
| 56 |
- Restoring the original test renderer |
|---|
| 57 |
- Restoring the email sending functions |
|---|
| 58 |
|
|---|
| 59 |
""" |
|---|
| 60 |
Template.render = Template.original_render |
|---|
| 61 |
del Template.original_render |
|---|
| 62 |
|
|---|
| 63 |
mail.SMTPConnection = mail.original_SMTPConnection |
|---|
| 64 |
del mail.original_SMTPConnection |
|---|
| 65 |
|
|---|
| 66 |
del mail.outbox |
|---|