#
# Copyright 2001 by Object Craft P/L, Melbourne, Australia.
#
# LICENCE - see LICENCE file distributed with this software for details.
#
# 
# Base class for testing Albatross functionality.
#
# Sub-classes are expected to define a class variable "template_dir" which
# tells albatross which directory to search for the html template files.
#
# There is also a class variable, self.ctx, available to classes derived
# from this which contains the current Albatross execution context.
#
# $Id: albatross_test.py,v 1.9 2002/07/30 07:33:51 andrewm Exp $

import unittest
import albatross

import sys
import os

class AlbatrossTestError(Exception):
    pass

app = albatross.Application('here')

class TestContext(albatross.TemplateLoaderMixin,
                  albatross.AppContext, albatross.NameRecorderMixin,
                  albatross.StubSessionMixin):
    def __init__(self, template_path):
        albatross.TemplateLoaderMixin.__init__(self, template_path)
        albatross.AppContext.__init__(self, app)
        albatross.NameRecorderMixin.__init__(self)

    def current_url(self):
        return 'here'

class AlbatrossTestCase(unittest.TestCase):
    def setUp(self):
        if not hasattr(self, "template_dir"):
            raise AlbatrossTestError("%s: template_dir not defined in class" % self.__class__)

        # This is because we may not be imported from the current directory
        base_dir = os.path.dirname(sys.modules[__name__].__file__)
        template_dir = os.path.join(base_dir, self.template_dir)

        self.ctx = TestContext(template_dir)

    def tearDown(self):
        pass

    # we use the content_trap to capture and return generated html;
    # html_flush() writes it to stdout directly.
    def gen_html(self, ctx, template):
        ctx.push_content_trap()
        tmpl = ctx.load_template(template)
        tmpl.to_html(ctx)
        return ctx.pop_content_trap()

    def html_test(self, template_file, expect):
        result = self.gen_html(self.ctx, template_file)
        self.assertEqual(result, expect, 'expected "%s", got "%s"' % (expect, result))
