Commits

jo...@cassee.net  committed 9dac563

* Added tests.
* Removed old test app.
* Removed unused code.

  • Participants
  • Parent commits 53b53b9

Comments (0)

Files changed (25)

File localeurl/__init__.py

 # Copyright (c) 2008 Joost Cassee
 # Licensed under the terms of the MIT License (see LICENSE.txt)
+
+import re
+from django.conf import settings
+
+SUPPORTED_LOCALES = dict(settings.LANGUAGES)
+LOCALES_RE = '|'.join(SUPPORTED_LOCALES)
+PATH_RE = re.compile(r'^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE)
+
+LOCALE_INDEPENDENT_PATHS = getattr(settings, 'LOCALE_INDEPENDENT_PATHS', ())
+
+LOCALE_INDEPENDENT_MEDIA_URL = getattr(settings,
+        'LOCALE_INDEPENDENT_MEDIA_URL', True)
+
+PREFIX_DEFAULT_LOCALE = getattr(settings, 'PREFIX_DEFAULT_LOCALE', True)

File localeurl/middleware.py

 # Copyright (c) 2008 Joost Cassee
 # Licensed under the terms of the MIT License (see LICENSE.txt)
 
-import re
-from django import http
 from django.conf import settings
 import django.core.exceptions
-from django.core import urlresolvers
 from django.http import HttpResponseRedirect
 from django.utils import translation
 import localeurl
             raise django.core.exceptions.MiddlewareNotUsed()
 
     def process_request(self, request):
-        locale, path = self.split_locale_from_request(request)
+        locale, path = utils.strip_path(request.path_info)
         locale_path = utils.locale_path(path, locale)
         if locale_path != request.path_info:
             if request.META.get("QUERY_STRING", ""):
             return HttpResponseRedirect(locale_path)
         request.path_info = path
         if not locale:
-            locale = settings.LANGUAGE_CODE
+            try:
+                locale = request.LANGUAGE_CODE
+            except AttributeError:
+                locale = settings.LANGUAGE_CODE
         translation.activate(locale)
         request.LANGUAGE_CODE = translation.get_language()
 
             response['Content-Language'] = translation.get_language()
         translation.deactivate()
         return response
-
-    def split_locale_from_request(self, request):
-        if localeurl.settings.URL_TYPE == 'domain':
-            raise AssertionError("URL_TYPE 'domain' not yet supported")
-        elif localeurl.settings.URL_TYPE == 'domain_component':
-            locale, _ = utils.strip_domain(request.get_host())
-            path_info = request.path_info
-        else:
-            locale, path_info = utils.strip_path(request.path_info)
-        return locale, path_info

File localeurl/models.py

-# Copyright (c) 2008 Joost Cassee
+# Copyright (c) 2008-2009 Joost Cassee
 # Licensed under the terms of the MIT License (see LICENSE.txt)
 
 from django.conf import settings
 from django.core import urlresolvers
 from django.utils import translation
-import localeurl
-import localeurl.settings
 from localeurl import utils
 
-if localeurl.settings.URL_TYPE == 'path_prefix' and settings.USE_I18N:
-    def reverse(*args, **kwargs):
-        reverse_kwargs = kwargs.get('kwargs', {})
-        locale = utils.supported_language(reverse_kwargs.pop('locale',
-                translation.get_language()))
-        path = django_reverse(*args, **kwargs)
-        return utils.locale_url(path, locale)
+def reverse(*args, **kwargs):
+    reverse_kwargs = kwargs.get('kwargs', {})
+    locale = utils.supported_language(reverse_kwargs.pop('locale',
+            translation.get_language()))
+    url = django_reverse(*args, **kwargs)
+    _, path = utils.strip_script_prefix(url)
+    return utils.locale_url(path, locale)
 
-    django_reverse = urlresolvers.reverse
-    urlresolvers.reverse = reverse
+django_reverse = None
+
+def patch_reverse():
+    """
+    Monkey-patches the urlresolvers.reverse function. Will not patch twice.
+    """
+    global django_reverse
+    if urlresolvers.reverse is not reverse:
+        django_reverse = urlresolvers.reverse
+        urlresolvers.reverse = reverse
+
+if settings.USE_I18N:
+    patch_reverse()

File localeurl/settings.py

-# Copyright (c) 2008 Joost Cassee
-# Licensed under the terms of the MIT License (see LICENSE.txt)
-
-from django.conf import settings
-
-URL_TYPES = ('path_prefix', 'domain_component', 'domain')
-URL_TYPE = getattr(settings, 'LOCALE_URL_TYPE', 'path_prefix')
-assert URL_TYPE in URL_TYPES, \
-        "LOCALE_URL_TYPE must be one of %s" % ', '.join(URL_TYPES)
-
-LOCALE_INDEPENDENT_PATHS = getattr(settings, 'LOCALE_INDEPENDENT_PATHS', ())
-assert not (URL_TYPE != 'path_prefix' and LOCALE_INDEPENDENT_PATHS), \
-        "LOCALE_INDEPENDENT_PATHS only used with URL_TYPE == 'path_prefix'"
-
-LOCALE_INDEPENDENT_MEDIA_URL = getattr(settings,
-        'LOCALE_INDEPENDENT_MEDIA_URL', True)
-
-PREFIX_DEFAULT_LOCALE = getattr(settings, 'PREFIX_DEFAULT_LOCALE', True)
-assert not (URL_TYPE != 'path_prefix' and PREFIX_DEFAULT_LOCALE), \
-        "PREFIX_DEFAULT_LOCALE only used with URL_TYPE == 'path_prefix'"
-
-DOMAINS = getattr(settings, 'LOCALE_DOMAINS', ())
-assert not (URL_TYPE != 'domain' and DOMAINS), \
-        "LOCALE_DOMAINS only used with URL_TYPE == 'domain'"

File localeurl/templatetags/localeurl_tags.py

 # Copyright (c) 2008 Joost Cassee
 # Licensed under the terms of the MIT License (see LICENSE.txt)
 
-from django.conf import settings
-from django.core.urlresolvers import get_script_prefix
 from django import template
 from django.template import Node, Token, TemplateSyntaxError
 from django.template import resolve_variable, defaulttags
 from django.template.defaultfilters import stringfilter
-from django.utils import translation
-import localeurl.settings
 from localeurl import utils
 
 register = template.Library()
     Changes the URL's locale prefix if the path is not locale-independent.
     Otherwise removes locale prefix.
     """
-    script_prefix, path = strip_script_prefix(url)
+    _, path = utils.strip_script_prefix(url)
     _, path = utils.strip_path(path)
     return utils.locale_url(path, locale)
 
 
 def rmlocale(url):
     """Removes the locale prefix from the URL."""
-    script_prefix, path = strip_script_prefix(url)
+    script_prefix, path = utils.strip_script_prefix(url)
     _, path = utils.strip_path(path)
     return ''.join([script_prefix, path])
 
 
     def render(self, context):
         locale = resolve_variable(self.locale, context)
+        if utils.supported_language(locale) is None:
+            raise ValueError("locale not in settings.LANGUAGES: %s" % locale)
         path = self.urlnode.render(context)
         if self.urlnode.asvar:
             self.urlnode.render(context)
             return chlocale(path, locale)
 
 register.tag('locale_url', locale_url)
-
-def strip_script_prefix(url):
-    """
-    Strips the SCRIPT_PREFIX from the URL. Because this function is meant for
-    use in templates, it assumes the URL starts with the prefix.
-    """
-    assert url.startswith(get_script_prefix()), \
-            "URL does not start with SCRIPT_PREFIX: %s" % url
-    pos = len(get_script_prefix()) - 1
-    return url[:pos], url[pos:]

File localeurl/test_settings.py

+"""
+Test settings.
+"""
+
+DATABASE_ENGINE = 'sqlite3'
+DATABASE_NAME = ':memory:'
+
+SITE_ID = 1
+
+ROOT_URLCONF = 'localeurl.test_urls'
+
+INSTALLED_APPS = (
+    'localeurl',
+)

File localeurl/test_urls.py

+"""
+URLconf for testing.
+"""
+
+from django.conf.urls.defaults import *
+
+urlpatterns = patterns('localeurl.test_urls',
+     url(r'^dummy/$', 'dummy', name='dummy0'),
+     url(r'^dummy/(?P<test>.+)$', 'dummy', name='dummy1'),
+)
+
+def dummy(request, test='test'):
+    pass

File localeurl/test_utils.py

+"""
+Test settings manager, originally copied from a `Django snippet`_ by 'carljm'.
+
+.. _`Django snippet`: http://www.djangosnippets.org/snippets/1011/
+"""
+
+from django.conf import settings as django_settings
+from django.core.handlers.wsgi import WSGIRequest
+from django.core.management import call_command
+from django.db.models import loading
+from django import template
+from django.test import Client
+from django.utils import encoding
+
+
+NO_SETTING = object()
+
+class TestSettingsManager(object):
+    """
+    A class which can modify some Django settings temporarily for a
+    test and then revert them to their original values later.
+
+    Automatically handles resyncing the DB if INSTALLED_APPS is
+    modified.
+
+    Based on the work by 'carljm':
+    http://www.djangosnippets.org/snippets/1011/
+    """
+    def __init__(self, settings=django_settings):
+        self._settings = settings
+        self._original_settings = {}
+
+    def set(self, **kwargs):
+        self.set_from_dict(kwargs)
+
+    def set_from_dict(self, settings):
+        for k,v in settings.iteritems():
+            self._original_settings.setdefault(k,
+                    getattr(self._settings, k, NO_SETTING))
+            setattr(self._settings, k, v)
+        if 'INSTALLED_APPS' in settings:
+            self.syncdb()
+
+    def syncdb(self):
+        loading.cache.loaded = False
+        call_command('syncdb', verbosity=0)
+
+    def revert(self):
+        for k,v in self._original_settings.iteritems():
+            if v == NO_SETTING:
+                try:
+                    delattr(self._settings, k)
+                except AttributeError:
+                    # Django < r11825
+                    delattr(self._settings._wrapped, k)
+            else:
+                setattr(self._settings, k, v)
+        if self._settings == django_settings \
+                and 'INSTALLED_APPS' in self._original_settings:
+            self.syncdb()
+        self._original_settings = {}
+
+
+class RequestFactory(Client):
+    """
+    Class that lets you create mock Request objects for use in testing.
+
+    Usage:
+
+    rf = RequestFactory()
+    get_request = rf.get('/hello/')
+    post_request = rf.post('/submit/', {'foo': 'bar'})
+
+    This class re-uses the django.test.client.Client interface, docs here:
+    http://www.djangoproject.com/documentation/testing/#the-test-client
+
+    Once you have a request object you can pass it to any view function,
+    just as if that view had been hooked up using a URLconf.
+
+    Based on the work by Simon Willison:
+    http://www.djangosnippets.org/snippets/963/
+    """
+    def request(self, **request):
+        """
+        Similar to parent class, but returns the request object as soon as it
+        has created it.
+        """
+        environ = {
+            'HTTP_COOKIE': self.cookies,
+            'PATH_INFO': '/',
+            'QUERY_STRING': '',
+            'REQUEST_METHOD': 'GET',
+            'SCRIPT_NAME': '',
+            'SERVER_NAME': 'testserver',
+            'SERVER_PORT': 80,
+            'SERVER_PROTOCOL': 'HTTP/1.1',
+        }
+        environ.update(self.defaults)
+        environ.update(request)
+        return WSGIRequest(environ)
+
+
+class TestTemplate(template.Template):
+    """
+    TestTemplate behaves just like django.template.Template, but you can give
+    it a list of template.Libraries to load before parsing the template. This
+    is equivalent to adding a bunch of {% load %} tags to the beginning of your
+    template string, but you can use custom tag libraries which do not belong
+    to Django applications' templatetags packages.
+
+    Based on the work by Alexander Khodyrev:
+    http://www.djangosnippets.org/snippets/1641/
+    """
+    def __init__(self, template_string, name='<Unknown Template>',
+            libraries=[]):
+        try:
+            template_string = encoding.smart_unicode(template_string)
+        except UnicodeDecodeError:
+            raise template.TemplateEncodingError(
+                    "template content must be unicode or UTF-8 string")
+        origin = template.StringOrigin(template_string)
+        self.nodelist = self.my_compile_string(template_string, origin,
+                libraries)
+        self.name = name
+
+    def my_compile_string(self, template_string, origin, libraries=[]):
+        "Compiles template_string into NodeList ready for rendering"
+        lexer = template.Lexer(template_string, origin)
+        parser = template.Parser(lexer.tokenize())
+        for lib in libraries:
+            parser.add_library(lib)
+        return parser.parse()

File localeurl/tests.py

+"""
+Tests for the localeurl application.
+"""
+
+import re
+import localeurl
+from localeurl import middleware
+from localeurl import test_utils
+from localeurl import utils
+from localeurl.templatetags import localeurl_tags
+
+from django.core import urlresolvers
+from django.test import TestCase
+from django import template
+
+def settings_fixture(mgr):
+    mgr.set(
+        INSTALLED_APPS = (
+            'localeurl',
+        ),
+        USE_I18N = True,
+        LANGUAGES = (
+            ('en', 'English'),
+            ('nl-nl', 'Dutch'),
+            ('nl-be', 'Flemish'),
+            ('fr', 'French'),
+        ),
+        LANGUAGE_CODE = 'en-gb',
+        LOCALE_INDEPENDENT_PATHS = (
+            re.compile('^/$'),
+            re.compile('^/test/independent/'),
+        ),
+        LOCALE_INDEPENDENT_MEDIA_URL = True,
+        MEDIA_URL = '/media/',
+        TEMPLATE_CONTEXT_PROCESSORS = (
+            'django.core.context_processors.i18n',
+        ),
+    )
+
+
+class LocaleurlTestCase(TestCase):
+    urls = 'localeurl.test_urls'
+
+    def setUp(self):
+        self.settings_manager = test_utils.TestSettingsManager()
+        settings_fixture(self.settings_manager)
+        reload(localeurl)
+        reload(urlresolvers)
+
+    def tearDown(self):
+        self.settings_manager.revert()
+        reload(localeurl)
+        reload(urlresolvers)
+
+
+class UtilsTestCase(LocaleurlTestCase):
+
+    def test_is_locale_independent(self):
+        self.assertFalse(utils.is_locale_independent('/fr/about'))
+        self.assertFalse(utils.is_locale_independent('/about'))
+        self.assertTrue(utils.is_locale_independent('/media/img/logo.png'))
+        self.assertTrue(utils.is_locale_independent('/'))
+        self.assertTrue(utils.is_locale_independent(
+                '/test/independent/bla/bla'))
+
+    def test_strip_path(self):
+        self.assertEqual(('', '/'), utils.strip_path('/'))
+        self.assertEqual(('', '/about/'), utils.strip_path('/about/'))
+        self.assertEqual(('', '/about/localeurl/'),
+                utils.strip_path('/about/localeurl/'))
+        self.assertEqual(('fr', '/about/localeurl/'),
+                utils.strip_path('/fr/about/localeurl/'))
+        self.assertEqual(('nl-be', '/about/localeurl/'),
+                utils.strip_path('/nl-be/about/localeurl/'))
+        self.assertEqual(('', '/de/about/localeurl/'),
+                utils.strip_path('/de/about/localeurl/'))
+
+    def test_supported_language(self):
+        self.assertEqual('fr', utils.supported_language('fr'))
+        self.assertEqual('nl-be', utils.supported_language('nl-be'))
+        self.assertEqual('en', utils.supported_language('en-gb'))
+        self.assertEqual(None, utils.supported_language('de'))
+
+    def test_is_default_locale(self):
+        self.assertTrue(utils.is_default_locale('en'))
+        self.assertFalse(utils.is_default_locale('en-gb'))
+        self.assertFalse(utils.is_default_locale('fr'))
+        self.assertFalse(utils.is_default_locale('de'))
+
+    def test_locale_path(self):
+        self.assertEqual('/en/about/localeurl/',
+                utils.locale_path('/about/localeurl/'))
+        self.assertEqual('/en/about/localeurl/',
+                utils.locale_path('/about/localeurl/', 'de'))
+        self.assertEqual('/en/about/localeurl/',
+                utils.locale_path('/about/localeurl/', 'en'))
+        self.assertEqual('/en/about/localeurl/',
+                utils.locale_path('/about/localeurl/', 'en-us'))
+        self.assertEqual('/nl-nl/about/localeurl/',
+                utils.locale_path('/about/localeurl/', 'nl-nl'))
+        self.assertEqual('/test/independent/bla/bla',
+                utils.locale_path('/test/independent/bla/bla', 'en'))
+
+    def test_locale_url(self):
+        # We'd like to be able to test using settings.FORCE_SCRIPT_NAME, but
+        # the urlresolvers module caches the prefix.
+        script_name = urlresolvers.get_script_prefix()
+        self.assertEqual(script_name + 'en/about/localeurl/',
+                utils.locale_url('/about/localeurl/'))
+        self.assertEqual(script_name + 'en/about/localeurl/',
+                utils.locale_url('/about/localeurl/', 'de'))
+        self.assertEqual(script_name + 'en/about/localeurl/',
+                utils.locale_url('/about/localeurl/', 'en'))
+        self.assertEqual(script_name + 'en/about/localeurl/',
+                utils.locale_url('/about/localeurl/', 'en-us'))
+        self.assertEqual(script_name + 'nl-nl/about/localeurl/',
+                utils.locale_url('/about/localeurl/', 'nl-nl'))
+        self.assertEqual(script_name + 'test/independent/bla/bla',
+                utils.locale_path('/test/independent/bla/bla', 'en'))
+
+
+class MiddlewareTestCase(LocaleurlTestCase):
+    def setUp(self):
+        super(MiddlewareTestCase, self).setUp()
+        self.request_factory = test_utils.RequestFactory()
+        self.middleware = middleware.LocaleURLMiddleware()
+
+    def test_process_request(self):
+        r1 = self.request_factory.get('/test/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(302, r2.status_code)
+        self.assertEqual('/en/test/', r2['Location'])
+
+        r1 = self.request_factory.get('/test/?somevar=someval')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(302, r2.status_code)
+        self.assertEqual('/en/test/?somevar=someval', r2['Location'])
+
+        r1 = self.request_factory.get('/fr/test/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(None, r2)
+        self.assertEqual('fr', r1.LANGUAGE_CODE)
+        self.assertEqual('/test/', r1.path_info)
+
+        r1 = self.request_factory.get('/nl-nl/test/bla/bla/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(None, r2)
+        self.assertEqual('nl-nl', r1.LANGUAGE_CODE)
+        self.assertEqual('/test/bla/bla/', r1.path_info)
+
+        r1 = self.request_factory.get('/test/independent/bla/bla/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(None, r2)
+        self.assertEqual('en-gb', r1.LANGUAGE_CODE)
+        self.assertEqual('/test/independent/bla/bla/', r1.path_info)
+
+        r1 = self.request_factory.get('/nl-be/test/independent/?foo=bar')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(302, r2.status_code)
+        self.assertEqual('/test/independent/?foo=bar', r2['Location'])
+
+    def test_process_request_no_default_prefix(self):
+        self.settings_manager.set(PREFIX_DEFAULT_LOCALE=False)
+        reload(localeurl)
+
+        r1 = self.request_factory.get('/test/foo/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(None, r2)
+        self.assertEqual('en-gb', r1.LANGUAGE_CODE)
+        self.assertEqual('/test/foo/', r1.path_info)
+
+        r1 = self.request_factory.get('/en/test/foo/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(302, r2.status_code)
+        self.assertEqual('/test/foo/', r2['Location'])
+
+        r1 = self.request_factory.get('/fr/test/foo/')
+        r2 = self.middleware.process_request(r1)
+        self.assertEqual(None, r2)
+        self.assertEqual('fr', r1.LANGUAGE_CODE)
+        self.assertEqual('/test/foo/', r1.path_info)
+
+
+class TagsTestCase(LocaleurlTestCase):
+    def render_template(self, text):
+        t = test_utils.TestTemplate(text, libraries=[localeurl_tags.register])
+        c = template.Context()
+        return t.render(c)
+
+    def test_locale_url_tag(self):
+        self.assertRaises(ValueError, self.render_template,
+                '{% locale_url "nl" dummy0 %}')
+
+        self.assertEqual('/en/dummy/', self.render_template(
+                '{% locale_url "en-us" dummy0 %}'))
+
+        self.assertEqual('/fr/dummy/4', self.render_template(
+            '{% locale_url "fr" dummy1 test=4 %}'))
+
+        self.assertEqual('/en/dummy/4', self.render_template(
+            '{% locale_url "en" dummy1 test=4 as testvar %}{{ testvar }}'))
+
+    def test_chlocale_filter(self):
+        self.assertEqual('/fr/dummy/', self.render_template(
+                '{{ "/dummy/"|chlocale:"fr" }}'))
+
+        self.assertEqual('/en/dummy/', self.render_template(
+                '{{"/fr/dummy/"|chlocale:"en-gb"}}'))
+
+    def test_rmlocale_filter(self):
+        self.assertEqual('/dummy/', self.render_template(
+                '{{ "/dummy/"|rmlocale }}'))
+
+        self.assertEqual('/dummy/', self.render_template(
+                '{{ "/nl-be/dummy/"|rmlocale }}'))
+
+        self.assertEqual('/dummy/', self.render_template(
+                '{{ "/en/dummy/"|rmlocale }}'))
+
+    def test_locale_url_tag_no_default_prefix(self):
+        self.settings_manager.set(PREFIX_DEFAULT_LOCALE=False)
+        reload(localeurl)
+
+        self.assertEqual('/dummy/', self.render_template(
+                '{% locale_url "en-us" dummy0 %}'))
+
+        self.assertEqual('/fr/dummy/', self.render_template(
+            '{% locale_url "fr" dummy0 %}'))
+
+    def test_chlocale_filter_no_default_prefix(self):
+        self.settings_manager.set(PREFIX_DEFAULT_LOCALE=False)
+        reload(localeurl)
+
+        self.assertEqual('/dummy/', self.render_template(
+                '{{ "/nl-nl/dummy/"|chlocale:"en-gb" }}'))
+
+        self.assertEqual('/fr/dummy/', self.render_template(
+                '{{"/nl-nl/dummy/"|chlocale:"fr"}}'))

File localeurl/utils.py

 # Copyright (c) 2008 Joost Cassee
 # Licensed under the terms of the MIT License (see LICENSE.txt)
 
-import re
 from django.conf import settings
 from django.core import urlresolvers
-import localeurl.settings
-
-SUPPORTED_LOCALES = dict(settings.LANGUAGES)
-LOCALES_RE = '|'.join(SUPPORTED_LOCALES)
-PATH_RE = re.compile(r'^/(?P<locale>%s)(?P<path>.*)$' % LOCALES_RE)
-DOMAIN_RE = re.compile(r'^(?P<locale>%s)\.(?P<domain>.*)$' % LOCALES_RE)
-DOMAIN_MAP = dict(localeurl.settings.DOMAINS)
+from django.core import urlresolvers
+import localeurl
 
 def is_locale_independent(path):
     """
     Returns whether the path is locale-independent.
     """
-    if localeurl.settings.LOCALE_INDEPENDENT_MEDIA_URL and settings.MEDIA_URL \
+    if localeurl.LOCALE_INDEPENDENT_MEDIA_URL and settings.MEDIA_URL \
             and path.startswith(settings.MEDIA_URL):
         return True
-    for regex in localeurl.settings.LOCALE_INDEPENDENT_PATHS:
+    for regex in localeurl.LOCALE_INDEPENDENT_PATHS:
         if regex.search(path):
             return True
     return False
     Separates the locale prefix from the rest of the path. If the path does not
     begin with a locale it is returned without change.
     """
-    if localeurl.settings.URL_TYPE == 'path_prefix':
-        check = PATH_RE.match(path)
-        if check:
-            path_info = check.group('path') or '/'
-            if path_info.startswith('/'):
-                return check.group('locale'), path_info
+    check = localeurl.PATH_RE.match(path)
+    if check:
+        path_info = check.group('path') or '/'
+        if path_info.startswith('/'):
+            return check.group('locale'), path_info
     return '', path
 
-def strip_domain(domain):
-    """
-    Returns the locale component and the domain without the locale component.
-    If the domain does not begin with a locale it is returned without change.
-    """
-    if localeurl.settings.URL_TYPE == 'domain_component':
-        check = DOMAIN_RE.match(domain)
-        if check:
-            return check.group('locale'), check.group('domain')
-    return '', domain
-
-def get_locale_from_domain(domain):
-    """
-    Returns the locale parsed from the domain.
-    """
-    raise AssertionError("Not implemented")
-    if localeurl.settings.URL_TYPE == 'domain':
-        if domain in DOMAIN_MAP:
-            return DOMAIN_MAP[domain]
-    return ''
-
 def supported_language(locale):
     """
     Returns the supported language (from settings.LANGUAGES) for the locale.
     """
-    if locale in SUPPORTED_LOCALES:
+    if locale in localeurl.SUPPORTED_LOCALES:
         return locale
-    elif locale[:2] in SUPPORTED_LOCALES:
+    elif locale[:2] in localeurl.SUPPORTED_LOCALES:
         return locale[:2]
     else:
         return None
     Generate the localeurl-enabled path from a path without locale prefix. If
     the locale is empty settings.LANGUAGE_CODE is used.
     """
-    if localeurl.settings.URL_TYPE != 'path_prefix':
-        return path
+    locale = supported_language(locale)
     if not locale:
         locale = supported_language(settings.LANGUAGE_CODE)
     if is_locale_independent(path):
         return path
-    elif is_default_locale(locale) \
-            and not localeurl.settings.PREFIX_DEFAULT_LOCALE:
+    elif is_default_locale(locale) and not localeurl.PREFIX_DEFAULT_LOCALE:
         return path
     else:
         return ''.join([u'/', locale, path])
     """
     path = locale_path(path, locale)
     return ''.join([urlresolvers.get_script_prefix(), path[1:]])
+
+def strip_script_prefix(url):
+    """
+    Strips the SCRIPT_PREFIX from the URL. Because this function is meant for
+    use in templates, it assumes the URL starts with the prefix.
+    """
+    assert url.startswith(urlresolvers.get_script_prefix()), \
+            "URL must start with SCRIPT_PREFIX: %s" % url
+    pos = len(urlresolvers.get_script_prefix()) - 1
+    return url[:pos], url[pos:]

File testlocaleurl/__init__.py

Empty file removed.

File testlocaleurl/manage.py

-#!/usr/bin/python
-
-import os
-import sys
-sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
-
-from django.core.management import execute_manager
-try:
-    import settings # Assumed to be in the same directory.
-except ImportError:
-    import sys
-    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
-    sys.exit(1)
-
-if __name__ == "__main__":
-    execute_manager(settings)

File testlocaleurl/settings.py

-# -*- coding: utf-8 -*-
-# Django settings for testlocaleurl project.
-
-import os
-import sys
-
-_ = lambda s: s  # dummy gettext function
-
-SRC_PATH = os.path.dirname(os.path.realpath(__file__))
-ROOT_PATH = os.path.dirname(SRC_PATH)
-sys.path.append(ROOT_PATH)
-
-DEBUG = True
-TEMPLATE_DEBUG = DEBUG
-
-DATABASE_ENGINE = 'sqlite3'    # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
-DATABASE_NAME = 'database.db'  # Or path to database file if using sqlite3.
-
-# Language code for this installation. All choices can be found here:
-# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
-# http://blogs.law.harvard.edu/tech/stories/storyReader$15
-LANGUAGE_CODE = 'nl-be'
-
-LANGUAGES = (
-    ('en-us', _(u'American English')),
-    ('en-gb', _(u'British English')),
-    ('nl', _(u'Nederlands')),
-    ('fr', _(u'Français')),
-)
-
-SITE_ID = 1
-
-# If you set this to False, Django will make some optimizations so as not
-# to load the internationalization machinery.
-USE_I18N = True
-
-# Absolute path to the directory that holds media.
-# Example: "/home/media/media.lawrence.com/"
-MEDIA_ROOT = ''
-
-# URL that handles the media served from MEDIA_ROOT.
-# Example: "http://media.lawrence.com"
-MEDIA_URL = '/media'
-
-# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
-# trailing slash.
-# Examples: "http://foo.com/media/", "/media/".
-ADMIN_MEDIA_PREFIX = '/media/'
-
-# Make this unique, and don't share it with anybody.
-SECRET_KEY = ')2kxmnsc@@0ot+5m5qka5+4wn4(b4=_l-!9($i@64wzm-7%3pu'
-
-# List of callables that know how to import templates from various sources.
-TEMPLATE_LOADERS = (
-    'django.template.loaders.filesystem.load_template_source',
-    'django.template.loaders.app_directories.load_template_source',
-#     'django.template.loaders.eggs.load_template_source',
-)
-
-MIDDLEWARE_CLASSES = (
-    'django.middleware.common.CommonMiddleware',
-    'django.contrib.sessions.middleware.SessionMiddleware',
-    'django.contrib.auth.middleware.AuthenticationMiddleware',
-    'django.middleware.doc.XViewMiddleware',
-    'localeurl.middleware.LocaleURLMiddleware',
-)
-
-TEMPLATE_CONTEXT_PROCESSORS = (
-    'django.core.context_processors.auth',
-    'django.core.context_processors.debug',
-    'django.core.context_processors.i18n',
-    'django.core.context_processors.request',
-)
-
-ROOT_URLCONF = 'testlocaleurl.urls'
-
-TEMPLATE_DIRS = (
-    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
-    # Always use forward slashes, even on Windows.
-    # Don't forget to use absolute paths, not relative paths.
-    SRC_PATH + '/templates'
-)
-
-INSTALLED_APPS = (
-    'django.contrib.auth',
-    'django.contrib.contenttypes',
-    'django.contrib.sessions',
-    'django.contrib.sites',
-    'localeurl',
-    'testapp',
-)
-
-import re
-LOCALE_INDEPENDENT_PATHS = (
-    re.compile('^/$'),
-    re.compile('^/test/independent/'),
-)

File testlocaleurl/templates/404.html

Empty file removed.

File testlocaleurl/templates/500.html

Empty file removed.

File testlocaleurl/testapp/__init__.py

Empty file removed.

File testlocaleurl/testapp/models.py

-from django.db import models
-
-# Create your models here.

File testlocaleurl/testapp/templates/chlocale.html

-{% load localeurl_tags %}
- {{ "/admin/"|chlocale:"nl" }} 
- {{ "/nl/admin/"|chlocale:"en-gb" }} 
- {{ "/en-us/admin/"|chlocale:LANGUAGE_CODE }} 

File testlocaleurl/testapp/templates/locale_url.html

-{% load localeurl_tags %}
- {% locale_url "nl" dummy0 %} 
- {% locale_url "en-us" dummy1 4 %} 
- {% locale_url "fr" dummy1 test=4 %} 
- {% locale_url "nl" dummy1 test=4 as testvar %}{{ testvar }} 

File testlocaleurl/testapp/templates/rmlocale.html

-{% load localeurl_tags %}
- {{ "/admin/"|rmlocale }} 
- {{ "/nl/admin/"|rmlocale }} 
- {{ "/en-us/admin/"|rmlocale }} 

File testlocaleurl/testapp/templates/test.html

Empty file removed.

File testlocaleurl/testapp/tests.py

-"""
-Tests for the localeurl application.
-
-    >>> import localeurl
-    >>> import localeurl.settings
-
-Module utils:
-
-    >>> from localeurl.utils import *
-
-    >>> is_locale_independent('/nl/about')
-    False
-    >>> is_locale_independent('/media/img/logo.png')
-    True
-    >>> is_locale_independent('/')
-    True
-    >>> is_locale_independent('/test/independent/bla/bla')
-    True
-
-    >>> strip_path('/')
-    ('', '/')
-    >>> strip_path('/about/')
-    ('', '/about/')
-    >>> strip_path('/about/localeurl/')
-    ('', '/about/localeurl/')
-    >>> strip_path('/fr/about/localeurl/')
-    ('fr', '/about/localeurl/')
-    >>> strip_path('/en-gb/about/localeurl/')
-    ('en-gb', '/about/localeurl/')
-    >>> strip_path('/pl/about/localeurl/')
-    ('', '/pl/about/localeurl/')
-
-Module middleware:
-
-    >>> from django.test.client import Client
-    >>> c = Client()
-
-    >>> r = c.get('/test/')
-    >>> r.status_code
-    302
-    >>> r['Location'] == 'http://testserver/nl/test/'
-    True
-
-    >>> r = c.get('/test/?somevar=somevalue')
-    >>> r.status_code
-    302
-    >>> r['Location'] == 'http://testserver/nl/test/?somevar=somevalue'
-    True
-
-    >>> r = c.get('/fr/test/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'fr'
-    True
-
-    >>> r = c.get('/en-us/test/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'en-us'
-    True
-
-    >>> r = c.get('/test/independent/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'nl-be'
-    True
-
-    >>> r = c.get('/test/independent/extra/path/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'nl-be'
-    True
-
-    >>> r = c.get('/en-us/test/independent/')
-    >>> r.status_code
-    302
-    >>> r['Location'] == 'http://testserver/test/independent/'
-    True
-
-    >>> r = c.get('/nl/test/independent/?somevar=somevalue')
-    >>> r.status_code
-    302
-    >>> r['Location'] == 'http://testserver/test/independent/?somevar=somevalue'
-    True
-
-Test middleware with default language not being prefixed:
-
-    (Changing the settings at runtime is a bit of a hack.)
-    >>> localeurl.settings.PREFIX_DEFAULT_LOCALE = False
-
-    >>> r = c.get('/test/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'nl-be'
-    True
-
-    >>> r = c.get('/nl/test/')
-    >>> r.status_code
-    302
-    >>> r['Location'] == 'http://testserver/test/'
-    True
-
-    >>> r = c.get('/fr/test/')
-    >>> r.status_code
-    200
-    >>> r.context['LANGUAGE_CODE'] == 'fr'
-    True
-
-    >>> localeurl.settings.PREFIX_DEFAULT_LOCALE = True
-
-Template tags and filters:
-
-    >>> r = c.get('/nl/test/locale_url/')
-    >>> r.status_code
-    200
-    >>> r.content
-    '\\n /nl/test/dummy/ \\n /en-us/test/dummy/4 \\n /fr/test/dummy/4 \\n /nl/test/dummy/4 \\n'
-
-    >>> r = c.get('/nl/test/chlocale/')
-    >>> r.status_code
-    200
-    >>> r.content
-    '\\n /nl/admin/ \\n /en-gb/admin/ \\n /nl/admin/ \\n'
-
-    >>> r = c.get('/nl/test/rmlocale/')
-    >>> r.status_code
-    200
-    >>> r.content
-    '\\n /admin/ \\n /admin/ \\n /admin/ \\n'
-
-Testing PREFIX_DEFAULT_LOCALE templatetags:
-
-    >>> localeurl.settings.PREFIX_DEFAULT_LOCALE = False
-
-    >>> r = c.get('/test/locale_url/')
-    >>> r.status_code
-    200
-    >>> r.content
-    '\\n /test/dummy/ \\n /en-us/test/dummy/4 \\n /fr/test/dummy/4 \\n /test/dummy/4 \\n'
-
-    >>> r = c.get('/fr/test/chlocale/')
-    >>> r.status_code
-    200
-    >>> r.content
-    '\\n /admin/ \\n /en-gb/admin/ \\n /fr/admin/ \\n'
-
-    >>> localeurl.settings.PREFIX_DEFAULT_LOCALE = True
-
-"""

File testlocaleurl/testapp/urls.py

-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('django.views.generic.simple',
-     (r'^$', 'direct_to_template', {'template': 'test.html'}),
-     (r'^independent/', 'direct_to_template', {'template': 'test.html'}),
-     (r'^locale_url/$', 'direct_to_template', {'template': 'locale_url.html'}),
-     (r'^chlocale/$', 'direct_to_template', {'template': 'chlocale.html'}),
-     (r'^rmlocale/$', 'direct_to_template', {'template': 'rmlocale.html'}),
-)
-
-urlpatterns += patterns('testapp.views',
-     url(r'^dummy/$', 'dummy', name='dummy0'),
-     url(r'^dummy/(?P<test>.+)$', 'dummy', name='dummy1'),
-)

File testlocaleurl/testapp/views.py

-from django.shortcuts import render_to_response
-
-def dummy(request, test=None):
-    return render_to_response('test.html')

File testlocaleurl/urls.py

-from django.conf.urls.defaults import *
-
-urlpatterns = patterns('',
-     (r'^test/', include('testlocaleurl.testapp.urls')),
-
-     #(r'^admin/', include('django.contrib.admin.urls')),
-)