# mako_django unit test integration.  To Install, 
# put this file somewhere in your python path, 
# and put the string
#  TEST_RUNNER=<python path to this file>
# in your settings.py file in your site. For example,
# if you install it at site-packages/mako_django/test_integration.py, 
# this would go in settings.py:
# TEST_RUNNER="mako_django.test_integration.run_mako_tests"

#**** This is ALPHA code (at best). ******

# Written by Erik Lee 

# You have my permission to do anything you want with it, except that
# you may not assume it is correct!

from django.test.utils import setup_test_environment, teardown_test_environment
from django.test.simple import run_tests
from mako.template import Template
from django.template.context import Context
from django.test import signals

def instrumented_test_render(self,**context):
    """
    This function calls the template's render function with the given
    rendering context, and then sends the template_rendered signal
    with the context and the template being rendered in order to
    integrate more fully with django's unit test system.
    """
    self.pretest_render(**context)
    signals.template_rendered.send(sender=self, template=self, context=Context(context))


def setup():
    """ 
    This function simply hijacks the mako template renderer's render
    function with a simple wrapper (instrumented_test_render) taht
    will trigger the template_rendered signal after rendering the
    template.  After the tests are run (using the default test runner
    provided in the django distribution, it restores the rendering
    function to its original state.  During the tests, the original
    function can be accessed through the name "pretest_render"
    """
    Template.pretest_render = Template.render
    Template.render = instrumented_test_render

def finish():
    """
    Restore the template renderer function to its original value
    """
    Template.render = Template.pretest_render    


def run_mako_tests(test_labels, verbosity, interactive):
    """
    Emulate the behavior of the django.test.simple.run_tests function
    """

    setup()
    result = run_tests(test_labels, verbosity, interactive)
    finish()
    return result