import django.test
import twill
from twill import commands as tc
from django.core.handlers.wsgi import WSGIHandler
from django.core.servers.basehttp import AdminMediaHandler 
from StringIO import StringIO
from django.test.client import Client
import mysite.base.controllers
import mysite.base.helpers

def twill_setup():
    app = AdminMediaHandler(WSGIHandler())
    twill.add_wsgi_intercept("127.0.0.1", 8080, lambda: app)

def twill_teardown():
    twill.remove_wsgi_intercept('127.0.0.1', 8080)
    tc.reset_browser()

def make_twill_url(url):
    # modify this
    return url.replace("http://openhatch.org/",
            "http://127.0.0.1:8080/")

def twill_quiet():
    # suppress normal output of twill.. You don't want to
    # call this if you want an interactive session
    twill.set_output(StringIO())

class TwillTests(django.test.TestCase):
    '''Some basic methods needed by other testing classes.'''
    # {{{
    def setUp(self):
        from django.conf import settings
        self.old_dbe = settings.DEBUG_PROPAGATE_EXCEPTIONS
        settings.DEBUG_PROPAGATE_EXCEPTIONS = True
        twill_setup()
        twill_quiet()

    def tearDown(self):
        # If you get an error on one of these lines,
        # maybe you didn't run base.TwillTests.setUp?
        from django.conf import settings
        settings.DEBUG_PROPAGATE_EXCEPTIONS = self.old_dbe
        twill_teardown()

    def login_with_twill(self):
        # Visit login page
        login_url = 'http://openhatch.org/account/login/old'
        tc.go(make_twill_url(login_url))

        # Log in
        username = "paulproteus"
        password = "paulproteus's unbreakable password"
        tc.fv('login', 'username', username)
        tc.fv('login', 'password', password)
        tc.submit()

    def login_with_client(self, username='paulproteus',
            password="paulproteus's unbreakable password"):
        client = Client()
        success = client.login(username=username,
                     password=password)
        self.assert_(success)
        return client

    def login_with_client_as_barry(self):
        return self.login_with_client(username='barry', password='parallelism')

    def signup_with_twill(self, username, email, password):
        """ Used by account.tests.Signup, which is omitted while we use invite codes. """
        pass

    # }}}

class LandingPage(TwillTests):
    # {{{
    fixtures = ['user-paulproteus', 'person-paulproteus']
    def test_show_landing_page_iff_logged_in(self):
        # {{{
        client = Client()
        response = client.get('/')
        self.assertTemplateUsed(response, 'base/homepage.html')

        client2 = self.login_with_client()
        response2 = client2.get('/')
        self.assertTemplateUsed(response2, 'base/landing.html')
        # }}}

    # }}}

class MySQLRegex(TwillTests):
    def test_escape(self):
        before2after = {
                'n': '[n]',
                ']': ']',
                '[n': '[[][n]'
                }
        for before, after in before2after.items():
            self.assertEqual(
                    mysite.base.controllers.mysql_regex_escape(before), 
                    after)

class TestUriDataHelper(TwillTests):
    def test(self):
        request = mysite.base.helpers.ObjectFromDict({
            'is_secure': lambda : True,
            'META': {'SERVER_PORT': '443',
                     'SERVER_NAME': 'name'}})
        data = mysite.base.controllers.get_uri_metadata_for_generating_absolute_links(request)
        self.assertEqual(data, {'uri_scheme': 'https',
                                'url_prefix': 'name'})

class Geocoder(TwillTests):
    def test_unicode_string(self):
        unicode_str = u'Bark\xe5ker, T\xf8nsberg, Vestfold, Norway'

        # Just exercise the geocoder and ensure it doesn't blow up.
        mysite.base.controllers.cached_geocoding_in_json(unicode_str)

# vim: set ai et ts=4 sw=4 nu:

@@ -293,16 +293,28 @@
 .helpers
+%0Aimport mock
 %0A%0Adef tw
@@ -3667,32 +3667,33 @@
 willTests):%0A
+%0A
     def 
 test_unicode
@@ -3680,20 +3680,41 @@
     def 
-test
+get_geocoding_in_json_for
 _unicode
@@ -3865,32 +3865,39 @@
 low up.%0A        
+return 
 mysite.base.cont
@@ -3943,16 +3943,1003 @@
 e_str)%0A%0A
+    def test_unicode_string(self):%0A        self.get_geocoding_in_json_for_unicode_string()%0A%0A    mock_geocoder = mock.Mock()%0A    @mock.patch(%22mysite.base.controllers._geocode%22, mock_geocoder)%0A    def test_unicode_strings_get_cached(self):%0A        # When the geocoder's results are being cached properly, %0A        # the base controller named '_geocode' will not run more than once.%0A        original_json = %22%7B'key': 'original value'%7D%22%0A        different_json = %22%7B'key': 'if caching works we should never get this value'%7D%22%0A        self.mock_geocoder.return_value = original_json %0A        self.assert_('original value' in self.get_geocoding_in_json_for_unicode_string()) %0A        self.mock_geocoder.return_value = different_json%0A        try:%0A            json = self.get_geocoding_in_json_for_unicode_string()%0A            self.assert_('original value' in json) %0A        except AssertionError:%0A            raise AssertionError, %22Geocoded location in json was not cached; it now equals %22 + json%0A%0A
 # vim: s

Write unsatisfied test that geocodings of unicode strings are being cached properly.