Skip to content

Commit

Permalink
Merge 8c5ce14 into c6af195
Browse files Browse the repository at this point in the history
  • Loading branch information
graingert committed Sep 20, 2018
2 parents c6af195 + 8c5ce14 commit 9cf3905
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 44 deletions.
5 changes: 1 addition & 4 deletions django_js_reverse/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,7 @@
except ImportError:
from django.core import urlresolvers

if sys.version < '3':
text_type = unicode # NOQA
else:
text_type = str
text_type = type(u'')

JS_IDENTIFIER_RE = re.compile(r'^[$A-Z_][\dA-Z_$]*$')

Expand Down
20 changes: 15 additions & 5 deletions django_js_reverse/templatetags/js_reverse.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,24 @@
register = template.Library()


urlconf = template.Variable('request.urlconf')


def _get_urlconf(context):
try:
return context.request.urlconf
except AttributeError:
pass
try:
return urlconf.resolve(context)
except template.VariableDoesNotExist:
pass


@register.simple_tag(takes_context=True)
def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = get_resolver(getattr(context['request'], 'urlconf', None))
else:
default_urlresolver = get_resolver(None)
return mark_safe(generate_js(default_urlresolver))
return mark_safe(generate_js(get_resolver(_get_urlconf(context))))
10 changes: 10 additions & 0 deletions django_js_reverse/tests/test_urlconf_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.conf.urls import include, url

def dummy_view():
pass

dummy_view()

urlpatterns = [
url(r'^test_changed_urlconf/$', dummy_view, name='test_changed_urlconf'),
]
13 changes: 3 additions & 10 deletions django_js_reverse/tests/test_urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,12 @@
except ImportError:
pass

if sys.version < '3':
import codecs

def u(x):
return codecs.unicode_escape_decode(x)[0]
else:
def u(x):
return x


def dummy_view(*args, **kwargs):
pass

dummy_view()


app_name = 'django_js_reverse'

Expand All @@ -36,7 +29,7 @@ def dummy_view(*args, **kwargs):
url(r'^test_two_url_args/(?P<arg_one>[-\w]+)-(?P<arg_two>[-\w]+)/$', dummy_view, name='test_two_url_args'),
url(r'^test_optional_url_arg/(?:1_(?P<arg_one>[-\w]+)-)?2_(?P<arg_two>[-\w]+)/$', dummy_view,
name='test_optional_url_arg'),
url(r'^test_unicode_url_name/$', dummy_view, name=u('test_unicode_url_name')),
url(r'^test_unicode_url_name/$', dummy_view, name=u'test_unicode_url_name'),
url(r'^test_duplicate_name/(?P<arg_one>[-\w]+)/$', dummy_view, name='test_duplicate_name'),
url(r'^test_duplicate_name/(?P<arg_one>[-\w]+)-(?P<arg_two>[-\w]+)/$', dummy_view, name='test_duplicate_name'),
url(r'^test_duplicate_argcount/(?P<arg_one>[-\w]+)?-(?P<arg_two>[-\w]+)?/$', dummy_view,
Expand Down
57 changes: 32 additions & 25 deletions django_js_reverse/tests/unit_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import subprocess
import sys
import unittest
import io

import django
from django.conf import settings
Expand All @@ -21,7 +22,7 @@
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..') + os.sep)
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from django.test import TestCase # noqa: E402 isort:skip
from django.test import TestCase, RequestFactory # noqa: E402 isort:skip
from django.test.client import Client # noqa: E402 isort:skip
from django.test.utils import override_settings # noqa: E402 isort:skip

Expand All @@ -35,9 +36,8 @@ def setUpClass(cls):
django.setup()
super(AbstractJSReverseTestCase, cls).setUpClass()

def assertEqualJSUrlEval(self, url_call, expected_url):
response = self.client.post('/jsreverse/')
script = '{}return {};'.format(smart_str(response.content), url_call)
def assertEqualJSEval(self, js, url_call, expected_url):
script = '{}return {};'.format(js, url_call)
module = 'console.log(new Function({})());'.format(json.dumps(script))
stdout = (
subprocess
Expand All @@ -47,6 +47,11 @@ def assertEqualJSUrlEval(self, url_call, expected_url):
self.assertEqual(re.sub(r'\n$', '', stdout), expected_url)


def assertEqualJSUrlEval(self, *args, **kwargs):
js = smart_str(self.client.post('/jsreverse/').content)
self.assertEqualJSEval(js, *args, **kwargs)


@override_settings(ROOT_URLCONF='django_js_reverse.tests.test_urls')
class JSReverseViewTestCaseMinified(AbstractJSReverseTestCase, TestCase):
def test_view_no_url_args(self):
Expand Down Expand Up @@ -212,15 +217,11 @@ def test_reverse_js_file_save(self):
call_command('collectstatic_js_reverse')

path = os.path.join(settings.STATIC_ROOT, 'django_js_reverse', 'js', 'reverse.js')
f = open(path)
f = io.open(path)
content1 = f.read()
if hasattr(content1, 'decode'):
content1 = content1.decode()

r2 = self.client.get('/jsreverse/')
content2 = r2.content
if hasattr(content2, 'decode'):
content2 = content2.decode()
content2 = r2.content.decode()

self.assertEqual(len(content1), len(content2), 'Static file don\'t match http response content_1')
self.assertEqual(content1, content2, 'Static file don\'t match http response content_2')
Expand All @@ -235,41 +236,47 @@ def test_reverse_js_file_save_with_output_path_option(self):
with override_settings(JS_REVERSE_OUTPUT_PATH=js_output_path):
call_command('collectstatic_js_reverse')

f = open(os.path.join(js_output_path, 'reverse.js'))
f = io.open(os.path.join(js_output_path, 'reverse.js'))
content1 = f.read()
if hasattr(content1, 'decode'):
content1 = content1.decode()

r2 = self.client.get('/jsreverse/')
content2 = r2.content
if hasattr(content2, 'decode'):
content2 = content2.decode()
content2 = r2.content.decode()

self.assertEqual(len(content1), len(content2), 'Static file don\'t match http response content_1')
self.assertEqual(content1, content2, 'Static file don\'t match http response content_2')

# should not raise ImproperlyConfigured exception if STATIC_ROOT is not set
with override_settings(STATIC_ROOT=None):
try:
call_command('collectstatic_js_reverse')
except ImproperlyConfigured:
self.fail(
'should not raise ImproperlyConfigured exception if STATIC_ROOT is not set and JS_REVERSE_OUTPUT_PATH is set')
call_command('collectstatic_js_reverse')

def test_script_prefix_noslash(self):
script_prefix = '/test/foo/bar'
with override_settings(JS_REVERSE_SCRIPT_PREFIX=script_prefix):
self.assertEqualJSUrlEval('Urls.test_no_url_args()', '{0}/test_no_url_args/'.format(script_prefix))

def test_script_prefix(self):

script_prefix = '/test/foo/bar/'
with override_settings(JS_REVERSE_SCRIPT_PREFIX=script_prefix):
self.assertEqualJSUrlEval('Urls.test_no_url_args()', '{0}test_no_url_args/'.format(script_prefix))




@override_settings(ROOT_URLCONF='django_js_reverse.tests.test_urls')
class JSReverseTemplateTagTest(AbstractJSReverseTestCase, TestCase):
def test_tpl_tag_with_request_in_context(self):
context_instance = RequestContext(self.client.request)
request = RequestFactory().post('/jsreverse/')
request.urlconf = 'django_js_reverse.tests.test_urlconf_urls'
tpl = Template('{% load js_reverse %}{% js_reverse_inline %}')
js_from_tag = tpl.render(context_instance)
js_from_view = smart_str(self.client.post('/jsreverse/').content)
self.assertEqual(js_from_tag, js_from_view)
js = tpl.render(RequestContext(request))
self.assertEqualJSEval(js, 'Urls.test_changed_urlconf()', '/test_changed_urlconf/')

def test_tpl_tag_with_dict_request_in_context(self):
request = {'urlconf': 'django_js_reverse.tests.test_urlconf_urls'}
tpl = Template('{% load js_reverse %}{% js_reverse_inline %}')
js = tpl.render(Context({'request': request}))
self.assertEqualJSEval(js, 'Urls.test_changed_urlconf()', '/test_changed_urlconf/')

def test_tpl_tag_without_request_in_context(self):
context_instance = Context()
Expand Down

0 comments on commit 9cf3905

Please sign in to comment.