"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/common.py $
$Id: common.py 30600 2008-03-14 11:04:24Z dbinger $
"""
import os
import os.path
import sys
from durus.utils import BytesIO, as_bytes
from qp.lib.site import Site
from qp.pub.common import get_publisher
try:
    from sancho.utest import UTest
except ImportError:
    UTest = object

def set_test_environment(input_string='', site_name=None, **env):
    env.setdefault('SCRIPT_NAME', '')
    env.setdefault('PATH_INFO', '/')
    env.setdefault('SERVER_NAME', 'example.org')
    from qp.pub.hit import Hit
    session_key = "test"
    stdout = sys.stdout
    if site_name is None:
        site_name = os.environ.get('SITE')
    publisher = Site(site_name).get_publisher()
    cookies='%s="%s"' % (publisher.get_site().get_name(), session_key)
    env['HTTP_COOKIE'] = cookies
    hit = Hit(BytesIO(as_bytes(input_string)), env)
    sys.stdout = stdout
    publisher.set_hit(hit)
    session = publisher.create_session()
    publisher.get_sessions()[session_key] = session
    hit.set_session(session)
    def nothing(*args):
        pass
    publisher.commit = nothing
    publisher.abort = nothing

class CommonTest (UTest):

    site_name = None

    def __init__(self, site_name=None):
        self.site_name = site_name
        UTest.__init__(self)

    def _pre(self):
        set_test_environment(site_name=self.site_name)
        get_publisher().get_connection().abort()

def format_user(user, **kwargs):
    return get_publisher().format_user(user, **kwargs)

def format_date(date):
    return get_publisher().format_date(date)

def format_date_time(date):
    return get_publisher().format_date_time(date)

def get_site_title():
    return get_publisher().get_site_title()
