from django.test import TestCase as DjangoTestCase
from django.db import transaction

from nose.tools import (
                assert_equals,
                assert_raises,
)

from selenium.driver import selenium as SeleniumClient

class SaneTestCase(object):
    """ Common ancestor we're using our own hierarchy """
    start_live_server = False
    test_types = ["unit"]
    
    def setUp(self):
        pass
    
    def assert_equals(self, *args, **kwargs):
        assert_equals(*args, **kwargs)
    
    assertEquals = assert_equals
    
    def assert_raises(self, *args, **kwargs):
        assert_raises(*args, **kwargs)
    
    assertRaises = assert_raises
    
    def tearDown(self):
        pass

class DatabaseTestCase(SaneTestCase):
    """ Tests using database for models: Rollback on teardown"""
    
    def setUp(self):
        transaction.enter_transaction_management()
        transaction.managed(True)
        SaneTestCase.setUp(self)
    
    def tearDown(self):
        transaction.rollback()
        transaction.leave_transaction_management()
        SaneTestCase.tearDown(self)
    
class HttpTestCase(SaneTestCase, DjangoTestCase):
    """
    If it is not running, our plugin should start HTTP server
    so we can use it with urllib2 or some webtester.
    """
    start_live_server = True
    test_types = ["http"]

class SeleniumTestCase(HttpTestCase):
    """
    Webtests using Selenium.
    """
    test_types = ["web"]

    def setUp(self):
        HttpTestCase.setUp(self)
        try:
            self.selenium = self.selenium_get()
        except Exception:
            raise SkipTest("Selenium not available")


    def selenium_get():
        if not hasattr(settings.SELENIUM_HOST) or not settings.SELENIUM_HOST:
            host = 'localhost'
        
        if not hasattr(settings.SELENIUM_PORT) or not settings.SELENIUM_PORT:
            port = 'localhost'

        if not hasattr(settings.SELENIUM_BROWSER_COMMAND) or not settings.SELENIUM_BROWSER_COMMAND:
            command = '*opera'

        if not hasattr(settings.URL_ROOT) or not settings.URL_ROOT:
            url_root = '/'
        
        
        sel = SeleniumClient(host, port, command, url_root)
        sel.start()
        return sel
    
    
