Skip to content

Commit

Permalink
Merge branch 'graingert-100-coverage' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
ierror committed May 5, 2019
2 parents ef8693e + 523b761 commit dd88d9d
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 95 deletions.
3 changes: 2 additions & 1 deletion .coveragerc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[run]
include=*/django_js_reverse*
omit=django_js_reverse/rjsmin.py
omit=django_js_reverse/rjsmin.py
branch = True
3 changes: 3 additions & 0 deletions CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@

New: Support for Django 2.2

New: Unit Tests Script prefix with no slash, changed URL Conf`#72 <https://github.com/ierror/django-js-reverse/issues/72>`__
Thank you `graingert <https://github.com/graingert>`__

Fix: "ROOT_URLCONF not taken into account" `#73 <https://github.com/ierror/django-js-reverse/issues/73>`__ `#74 <https://github.com/ierror/django-js-reverse/issues/74>`__
Thank you `LuukOost <https://github.com/LuukOost>`__ and `graingert <https://github.com/graingert>`__

Expand Down
3 changes: 3 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ _________

New: Support for Django 2.2

New: Unit Tests Script prefix with no slash, changed URL Conf`#72 <https://github.com/ierror/django-js-reverse/issues/72>`__
Thank you `graingert <https://github.com/graingert>`__

Fix: "ROOT_URLCONF not taken into account" `#73 <https://github.com/ierror/django-js-reverse/issues/73>`__ `#74 <https://github.com/ierror/django-js-reverse/issues/74>`__
Thank you `LuukOost <https://github.com/LuukOost>`__ and `graingert <https://github.com/graingert>`__

Expand Down
2 changes: 1 addition & 1 deletion django_js_reverse/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def generate_js(default_urlresolver):
if not script_prefix.endswith('/'):
script_prefix = '{0}/'.format(script_prefix)
else:
script_prefix = None
script_prefix = urlresolvers.get_script_prefix()

data = generate_json(default_urlresolver, script_prefix)
js_content = loader.render_to_string('django_js_reverse/urls_js.tpl', {
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))))
6 changes: 6 additions & 0 deletions django_js_reverse/tests/test_urlconf_urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.views.generic import View
from django.conf.urls import url

urlpatterns = [
url(r'^test_changed_urlconf/$', View.as_view(), name='test_changed_urlconf'),
]
89 changes: 28 additions & 61 deletions django_js_reverse/tests/test_urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
import sys
from copy import copy

from django.conf.urls import include, url
from django.conf.urls import include as django_include, url
from django.views.generic import View
from django_js_reverse.tests.helper import is_django_ver_gte_2
from django_js_reverse.views import urls_js

Expand All @@ -11,21 +11,8 @@
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


app_name = 'django_js_reverse'
dummy_view = View.as_view()

basic_patterns = [
url(r'^jsreverse/$', urls_js, name='js_reverse'),
Expand All @@ -36,7 +23,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 All @@ -57,68 +44,48 @@ def dummy_view(*args, **kwargs):
name='test_exclude_namespace_url1')
]


def include(v, **kwargs):
if not is_django_ver_gte_2():
return django_include(v, **kwargs)

return django_include((v, 'django_js_reverse'), **kwargs)


# test namespace
pattern_ns_1 = [
url(r'', include(basic_patterns))
url(r'', django_include(basic_patterns))
]

pattern_ns_2 = [
url(r'', include(basic_patterns))
url(r'', django_include(basic_patterns))
]

pattern_ns_arg = [
url(r'', include(basic_patterns))
pattern_ns = [
url(r'', django_include(basic_patterns))
]

if is_django_ver_gte_2():
urlexclude = (urlexclude, 'django_js_reverse')
pattern_ns_1_arg = (pattern_ns_1, 'django_js_reverse')
pattern_ns_2_arg = (pattern_ns_2, 'django_js_reverse')
pattern_ns_arg_arg = (pattern_ns_arg, 'django_js_reverse')
else:
urlexclude = urlexclude
pattern_ns_1_arg = pattern_ns_1
pattern_ns_2_arg = pattern_ns_2
pattern_ns_arg_arg = pattern_ns_arg

pattern_nested_ns = [
url(r'^ns1/', include(pattern_ns_1_arg, namespace='ns1'))
url(r'^ns1/', include(pattern_ns_1, namespace='ns1'))
]

pattern_dubble_nested2_ns = [
url(r'^ns1/', include(pattern_ns_1_arg, namespace='ns1'))]

if is_django_ver_gte_2():
pattern_nested_ns_arg = (pattern_nested_ns, 'django_js_reverse')
pattern_dubble_nested2_ns_arg = (pattern_dubble_nested2_ns, 'django_js_reverse')
else:
pattern_nested_ns_arg = pattern_nested_ns
pattern_dubble_nested2_ns_arg = pattern_dubble_nested2_ns
url(r'^ns1/', include(pattern_ns_1, namespace='ns1'))]

pattern_dubble_nested_ns = [
url(r'^ns1/', include(pattern_ns_1_arg, namespace='ns1')),
url(r'^nsdn2/', include(pattern_dubble_nested2_ns_arg, namespace='nsdn2'))]

if is_django_ver_gte_2():
pattern_dubble_nested_ns_arg = (pattern_dubble_nested_ns, 'django_js_reverse')
else:
pattern_dubble_nested_ns_arg = pattern_dubble_nested_ns
url(r'^ns1/', include(pattern_ns_1, namespace='ns1')),
url(r'^nsdn2/', include(pattern_dubble_nested2_ns, namespace='nsdn2'))]

pattern_only_nested_ns = [
url(r'^ns1/', include(pattern_ns_1)),
url(r'^nsdn0/', include(pattern_dubble_nested2_ns_arg, namespace='nsdn0'))]

if is_django_ver_gte_2():
pattern_only_nested_ns_arg = (pattern_only_nested_ns, 'django_js_reverse')
else:
pattern_only_nested_ns_arg = pattern_only_nested_ns
url(r'^ns1/', django_include(pattern_ns_1)),
url(r'^nsdn0/', include(pattern_dubble_nested2_ns, namespace='nsdn0'))]

urlpatterns += [
url(r'^ns1/', include(pattern_ns_1_arg, namespace='ns1')),
url(r'^ns2/', include(pattern_ns_2_arg, namespace='ns2')),
url(r'^ns1/', include(pattern_ns_1, namespace='ns1')),
url(r'^ns2/', include(pattern_ns_2, namespace='ns2')),
url(r'^ns_ex/', include(urlexclude, namespace='exclude_namespace')),
url(r'^ns(?P<ns_arg>[^/]*)/', include(pattern_ns_arg_arg, namespace='ns_arg')),
url(r'^nestedns/', include(pattern_nested_ns_arg, namespace='nestedns')),
url(r'^nsdn/', include(pattern_dubble_nested_ns_arg, namespace='nsdn')),
url(r'^nsno/', include(pattern_only_nested_ns_arg, namespace='nsno'))
url(r'^ns(?P<ns_arg>[^/]*)/', include(pattern_ns, namespace='ns_arg')),
url(r'^nestedns/', include(pattern_nested_ns, namespace='nestedns')),
url(r'^nsdn/', include(pattern_dubble_nested_ns, namespace='nsdn')),
url(r'^nsno/', include(pattern_only_nested_ns, namespace='nsno'))
]
60 changes: 33 additions & 27 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 @@ -36,9 +37,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,10 @@ 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):
Expand Down Expand Up @@ -144,7 +148,7 @@ def test_only_namespaces_without_subnss(self):
'/nsno/ns1/test_two_url_args/arg_one-arg_two/')
self.assertNotContains(response, 'nsno:nsdn0', status_code=200)

def test_script_prefix(self):
def test_script_prefix_v1(self):
with script_prefix('/foobarlala/'):
self.assertEqualJSUrlEval('Urls["nestedns:ns1:test_two_url_args"]("arg_one", "arg_two")',
'/foobarlala/nestedns/ns1/test_two_url_args/arg_one-arg_two/')
Expand Down Expand Up @@ -216,15 +220,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 @@ -239,41 +239,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')
@override_settings(
ROOT_URLCONF='django_js_reverse.tests.test_urls',
TEMPLATE_CONTEXT_PROCESSORS=['django.core.context_processors.request'],
)
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 dd88d9d

Please sign in to comment.