#
# Copyright 2001 by Object Craft P/L, Melbourne, Australia.
#
# LICENCE - see LICENCE file distributed with this software for details.
#
#
# SessionFile functionality tests
#
# $Id: ses_file.py,v 1.7 2003/09/21 04:40:31 djc Exp $
#

import os, sys, errno

import unittest
import albatross

import request

class Vars:
    pass

class SessionFileApp(albatross.SessionFileAppMixin):
    def module_path(self):
        pass

class SessionFile(albatross.ResponseMixin, albatross.SessionFileContextMixin):
    """ 
    This corresponds to the object albatross users know as the ctx,
    although since we aren't using the normal set of mixins, we have to
    supply our own locals and request members.
    """
    def __init__(self, request, test_dir):
        self.app = SessionFileApp('test', test_dir)
        self.request = request
        self.locals = Vars()
        albatross.ResponseMixin.__init__(self)
        albatross.SessionFileContextMixin.__init__(self)

    def absolute_base_url(self):
        return ''

    def test_save(self):
        self.write_headers()
        self.save_session()

class Session:
    """
    This represents a virtual "user" - essentially just a place to store
    their session id while the ctx objects come and go.
    """
    def __init__(self, test_dir):
        self.test_dir = test_dir
        self.request = request.DummyCookieRequest()

    def new_context(self):
        return SessionFile(self.request, self.test_dir)

class FileCase(unittest.TestCase):
    def setUp(self):
        # This is because we may not be imported from the current directory
        try:
            base_dir = os.path.dirname(sys.modules[__name__].__file__)
        except AttributeError:
            base_dir = ''
        self.test_dir = os.path.join(base_dir, "sessionfiletmp")
        try:
            os.mkdir(self.test_dir)
        except OSError, (eno, estr):
            if eno == errno.EEXIST:
                self.cleandir(self.test_dir)
            else:
                raise OSError, (eno, estr)

    def tearDown(self):
        self.cleandir(self.test_dir)
        os.rmdir(self.test_dir)

    def cleandir(self, test_dir):
        for file in os.listdir(test_dir):
            if file[-4:] == '.als':             # Safety
                os.unlink(os.path.join(test_dir, file))

    def new_session(self):
        return Session(self.test_dir)
