web/lib/django/test/utils.py
changeset 29 cc9b7e14412b
parent 0 0d40e90630ef
--- a/web/lib/django/test/utils.py	Wed May 19 17:43:59 2010 +0200
+++ b/web/lib/django/test/utils.py	Tue May 25 02:43:45 2010 +0200
@@ -1,7 +1,7 @@
 import sys, time, os
 from django.conf import settings
-from django.db import connection
 from django.core import mail
+from django.core.mail.backends import locmem
 from django.test import signals
 from django.template import Template
 from django.utils.translation import deactivate
@@ -15,7 +15,7 @@
             for subcontext in self:
                 if key in subcontext:
                     return subcontext[key]
-            raise KeyError
+            raise KeyError(key)
         else:
             return super(ContextList, self).__getitem__(key)
 
@@ -28,37 +28,22 @@
     signals.template_rendered.send(sender=self, template=self, context=context)
     return self.nodelist.render(context)
 
-class TestSMTPConnection(object):
-    """A substitute SMTP connection for use during test sessions.
-    The test connection stores email messages in a dummy outbox,
-    rather than sending them out on the wire.
-
-    """
-    def __init__(*args, **kwargs):
-        pass
-    def open(self):
-        "Mock the SMTPConnection open() interface"
-        pass
-    def close(self):
-        "Mock the SMTPConnection close() interface"
-        pass
-    def send_messages(self, messages):
-        "Redirect messages to the dummy outbox"
-        mail.outbox.extend(messages)
-        return len(messages)
 
 def setup_test_environment():
     """Perform any global pre-test setup. This involves:
 
         - Installing the instrumented test renderer
-        - Diverting the email sending functions to a test buffer
+        - Set the email backend to the locmem email backend.
         - Setting the active locale to match the LANGUAGE_CODE setting.
     """
-    Template.original_render = Template.render
-    Template.render = instrumented_test_render
+    Template.original_render = Template._render
+    Template._render = instrumented_test_render
 
     mail.original_SMTPConnection = mail.SMTPConnection
-    mail.SMTPConnection = TestSMTPConnection
+    mail.SMTPConnection = locmem.EmailBackend
+
+    mail.original_email_backend = settings.EMAIL_BACKEND
+    settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
 
     mail.outbox = []
 
@@ -71,15 +56,17 @@
         - Restoring the email sending functions
 
     """
-    Template.render = Template.original_render
+    Template._render = Template.original_render
     del Template.original_render
 
     mail.SMTPConnection = mail.original_SMTPConnection
     del mail.original_SMTPConnection
 
+    settings.EMAIL_BACKEND = mail.original_email_backend
+    del mail.original_email_backend
+
     del mail.outbox
 
-
 def get_runner(settings):
     test_path = settings.TEST_RUNNER.split('.')
     # Allow for Python 2.5 relative paths