tests.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. import string
  2. import uuid
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.test import SimpleTestCase
  5. from django.test.utils import override_settings
  6. from django.urls import NoReverseMatch, Resolver404, path, resolve, reverse
  7. from .converters import DynamicConverter
  8. from .views import empty_view
  9. included_kwargs = {'base': b'hello', 'value': b'world'}
  10. converter_test_data = (
  11. # ('url', ('url_name', 'app_name', {kwargs})),
  12. # aGVsbG8= is 'hello' encoded in base64.
  13. ('/base64/aGVsbG8=/', ('base64', '', {'value': b'hello'})),
  14. ('/base64/aGVsbG8=/subpatterns/d29ybGQ=/', ('subpattern-base64', '', included_kwargs)),
  15. ('/base64/aGVsbG8=/namespaced/d29ybGQ=/', ('subpattern-base64', 'namespaced-base64', included_kwargs)),
  16. )
  17. @override_settings(ROOT_URLCONF='urlpatterns.path_urls')
  18. class SimplifiedURLTests(SimpleTestCase):
  19. def test_path_lookup_without_parameters(self):
  20. match = resolve('/articles/2003/')
  21. self.assertEqual(match.url_name, 'articles-2003')
  22. self.assertEqual(match.args, ())
  23. self.assertEqual(match.kwargs, {})
  24. self.assertEqual(match.route, 'articles/2003/')
  25. def test_path_lookup_with_typed_parameters(self):
  26. match = resolve('/articles/2015/')
  27. self.assertEqual(match.url_name, 'articles-year')
  28. self.assertEqual(match.args, ())
  29. self.assertEqual(match.kwargs, {'year': 2015})
  30. self.assertEqual(match.route, 'articles/<int:year>/')
  31. def test_path_lookup_with_multiple_parameters(self):
  32. match = resolve('/articles/2015/04/12/')
  33. self.assertEqual(match.url_name, 'articles-year-month-day')
  34. self.assertEqual(match.args, ())
  35. self.assertEqual(match.kwargs, {'year': 2015, 'month': 4, 'day': 12})
  36. self.assertEqual(match.route, 'articles/<int:year>/<int:month>/<int:day>/')
  37. def test_two_variable_at_start_of_path_pattern(self):
  38. match = resolve('/en/foo/')
  39. self.assertEqual(match.url_name, 'lang-and-path')
  40. self.assertEqual(match.kwargs, {'lang': 'en', 'url': 'foo'})
  41. self.assertEqual(match.route, '<lang>/<path:url>/')
  42. def test_re_path(self):
  43. match = resolve('/regex/1/')
  44. self.assertEqual(match.url_name, 'regex')
  45. self.assertEqual(match.kwargs, {'pk': '1'})
  46. self.assertEqual(match.route, '^regex/(?P<pk>[0-9]+)/$')
  47. def test_re_path_with_optional_parameter(self):
  48. for url, kwargs in (
  49. ('/regex_optional/1/2/', {'arg1': '1', 'arg2': '2'}),
  50. ('/regex_optional/1/', {'arg1': '1'}),
  51. ):
  52. with self.subTest(url=url):
  53. match = resolve(url)
  54. self.assertEqual(match.url_name, 'regex_optional')
  55. self.assertEqual(match.kwargs, kwargs)
  56. self.assertEqual(
  57. match.route,
  58. r'^regex_optional/(?P<arg1>\d+)/(?:(?P<arg2>\d+)/)?',
  59. )
  60. def test_re_path_with_missing_optional_parameter(self):
  61. match = resolve('/regex_only_optional/')
  62. self.assertEqual(match.url_name, 'regex_only_optional')
  63. self.assertEqual(match.kwargs, {})
  64. self.assertEqual(match.args, ())
  65. self.assertEqual(
  66. match.route,
  67. r'^regex_only_optional/(?:(?P<arg1>\d+)/)?',
  68. )
  69. def test_path_lookup_with_inclusion(self):
  70. match = resolve('/included_urls/extra/something/')
  71. self.assertEqual(match.url_name, 'inner-extra')
  72. self.assertEqual(match.route, 'included_urls/extra/<extra>/')
  73. def test_path_lookup_with_empty_string_inclusion(self):
  74. match = resolve('/more/99/')
  75. self.assertEqual(match.url_name, 'inner-more')
  76. self.assertEqual(match.route, r'^more/(?P<extra>\w+)/$')
  77. def test_path_lookup_with_double_inclusion(self):
  78. match = resolve('/included_urls/more/some_value/')
  79. self.assertEqual(match.url_name, 'inner-more')
  80. self.assertEqual(match.route, r'included_urls/more/(?P<extra>\w+)/$')
  81. def test_path_reverse_without_parameter(self):
  82. url = reverse('articles-2003')
  83. self.assertEqual(url, '/articles/2003/')
  84. def test_path_reverse_with_parameter(self):
  85. url = reverse('articles-year-month-day', kwargs={'year': 2015, 'month': 4, 'day': 12})
  86. self.assertEqual(url, '/articles/2015/4/12/')
  87. @override_settings(ROOT_URLCONF='urlpatterns.path_base64_urls')
  88. def test_converter_resolve(self):
  89. for url, (url_name, app_name, kwargs) in converter_test_data:
  90. with self.subTest(url=url):
  91. match = resolve(url)
  92. self.assertEqual(match.url_name, url_name)
  93. self.assertEqual(match.app_name, app_name)
  94. self.assertEqual(match.kwargs, kwargs)
  95. @override_settings(ROOT_URLCONF='urlpatterns.path_base64_urls')
  96. def test_converter_reverse(self):
  97. for expected, (url_name, app_name, kwargs) in converter_test_data:
  98. if app_name:
  99. url_name = '%s:%s' % (app_name, url_name)
  100. with self.subTest(url=url_name):
  101. url = reverse(url_name, kwargs=kwargs)
  102. self.assertEqual(url, expected)
  103. @override_settings(ROOT_URLCONF='urlpatterns.path_base64_urls')
  104. def test_converter_reverse_with_second_layer_instance_namespace(self):
  105. kwargs = included_kwargs.copy()
  106. kwargs['last_value'] = b'world'
  107. url = reverse('instance-ns-base64:subsubpattern-base64', kwargs=kwargs)
  108. self.assertEqual(url, '/base64/aGVsbG8=/subpatterns/d29ybGQ=/d29ybGQ=/')
  109. def test_path_inclusion_is_matchable(self):
  110. match = resolve('/included_urls/extra/something/')
  111. self.assertEqual(match.url_name, 'inner-extra')
  112. self.assertEqual(match.kwargs, {'extra': 'something'})
  113. def test_path_inclusion_is_reversible(self):
  114. url = reverse('inner-extra', kwargs={'extra': 'something'})
  115. self.assertEqual(url, '/included_urls/extra/something/')
  116. def test_invalid_converter(self):
  117. msg = "URL route 'foo/<nonexistent:var>/' uses invalid converter 'nonexistent'."
  118. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  119. path('foo/<nonexistent:var>/', empty_view)
  120. def test_invalid_view(self):
  121. msg = 'view must be a callable or a list/tuple in the case of include().'
  122. with self.assertRaisesMessage(TypeError, msg):
  123. path('articles/', 'invalid_view')
  124. def test_whitespace_in_route(self):
  125. msg = (
  126. "URL route 'space/<int:num>/extra/<str:%stest>' cannot contain "
  127. "whitespace in angle brackets <…>"
  128. )
  129. for whitespace in string.whitespace:
  130. with self.subTest(repr(whitespace)):
  131. with self.assertRaisesMessage(ImproperlyConfigured, msg % whitespace):
  132. path('space/<int:num>/extra/<str:%stest>' % whitespace, empty_view)
  133. # Whitespaces are valid in paths.
  134. p = path('space%s/<int:num>/' % string.whitespace, empty_view)
  135. match = p.resolve('space%s/1/' % string.whitespace)
  136. self.assertEqual(match.kwargs, {'num': 1})
  137. @override_settings(ROOT_URLCONF='urlpatterns.converter_urls')
  138. class ConverterTests(SimpleTestCase):
  139. def test_matching_urls(self):
  140. def no_converter(x):
  141. return x
  142. test_data = (
  143. ('int', {'0', '1', '01', 1234567890}, int),
  144. ('str', {'abcxyz'}, no_converter),
  145. ('path', {'allows.ANY*characters'}, no_converter),
  146. ('slug', {'abcxyz-ABCXYZ_01234567890'}, no_converter),
  147. ('uuid', {'39da9369-838e-4750-91a5-f7805cd82839'}, uuid.UUID),
  148. )
  149. for url_name, url_suffixes, converter in test_data:
  150. for url_suffix in url_suffixes:
  151. url = '/%s/%s/' % (url_name, url_suffix)
  152. with self.subTest(url=url):
  153. match = resolve(url)
  154. self.assertEqual(match.url_name, url_name)
  155. self.assertEqual(match.kwargs, {url_name: converter(url_suffix)})
  156. # reverse() works with string parameters.
  157. string_kwargs = {url_name: url_suffix}
  158. self.assertEqual(reverse(url_name, kwargs=string_kwargs), url)
  159. # reverse() also works with native types (int, UUID, etc.).
  160. if converter is not no_converter:
  161. # The converted value might be different for int (a
  162. # leading zero is lost in the conversion).
  163. converted_value = match.kwargs[url_name]
  164. converted_url = '/%s/%s/' % (url_name, converted_value)
  165. self.assertEqual(reverse(url_name, kwargs={url_name: converted_value}), converted_url)
  166. def test_nonmatching_urls(self):
  167. test_data = (
  168. ('int', {'-1', 'letters'}),
  169. ('str', {'', '/'}),
  170. ('path', {''}),
  171. ('slug', {'', 'stars*notallowed'}),
  172. ('uuid', {
  173. '',
  174. '9da9369-838e-4750-91a5-f7805cd82839',
  175. '39da9369-838-4750-91a5-f7805cd82839',
  176. '39da9369-838e-475-91a5-f7805cd82839',
  177. '39da9369-838e-4750-91a-f7805cd82839',
  178. '39da9369-838e-4750-91a5-f7805cd8283',
  179. }),
  180. )
  181. for url_name, url_suffixes in test_data:
  182. for url_suffix in url_suffixes:
  183. url = '/%s/%s/' % (url_name, url_suffix)
  184. with self.subTest(url=url), self.assertRaises(Resolver404):
  185. resolve(url)
  186. @override_settings(ROOT_URLCONF='urlpatterns.path_same_name_urls')
  187. class SameNameTests(SimpleTestCase):
  188. def test_matching_urls_same_name(self):
  189. @DynamicConverter.register_to_url
  190. def requires_tiny_int(value):
  191. if value > 5:
  192. raise ValueError
  193. return value
  194. tests = [
  195. ('number_of_args', [
  196. ([], {}, '0/'),
  197. ([1], {}, '1/1/'),
  198. ]),
  199. ('kwargs_names', [
  200. ([], {'a': 1}, 'a/1/'),
  201. ([], {'b': 1}, 'b/1/'),
  202. ]),
  203. ('converter', [
  204. (['a/b'], {}, 'path/a/b/'),
  205. (['a b'], {}, 'str/a%20b/'),
  206. (['a-b'], {}, 'slug/a-b/'),
  207. (['2'], {}, 'int/2/'),
  208. (
  209. ['39da9369-838e-4750-91a5-f7805cd82839'],
  210. {},
  211. 'uuid/39da9369-838e-4750-91a5-f7805cd82839/'
  212. ),
  213. ]),
  214. ('regex', [
  215. (['ABC'], {}, 'uppercase/ABC/'),
  216. (['abc'], {}, 'lowercase/abc/'),
  217. ]),
  218. ('converter_to_url', [
  219. ([6], {}, 'int/6/'),
  220. ([1], {}, 'tiny_int/1/'),
  221. ]),
  222. ]
  223. for url_name, cases in tests:
  224. for args, kwargs, url_suffix in cases:
  225. expected_url = '/%s/%s' % (url_name, url_suffix)
  226. with self.subTest(url=expected_url):
  227. self.assertEqual(
  228. reverse(url_name, args=args, kwargs=kwargs),
  229. expected_url,
  230. )
  231. class ParameterRestrictionTests(SimpleTestCase):
  232. def test_integer_parameter_name_causes_exception(self):
  233. msg = (
  234. "URL route 'hello/<int:1>/' uses parameter name '1' which isn't "
  235. "a valid Python identifier."
  236. )
  237. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  238. path(r'hello/<int:1>/', lambda r: None)
  239. def test_non_identifier_parameter_name_causes_exception(self):
  240. msg = (
  241. "URL route 'b/<int:book.id>/' uses parameter name 'book.id' which "
  242. "isn't a valid Python identifier."
  243. )
  244. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  245. path(r'b/<int:book.id>/', lambda r: None)
  246. def test_allows_non_ascii_but_valid_identifiers(self):
  247. # \u0394 is "GREEK CAPITAL LETTER DELTA", a valid identifier.
  248. p = path('hello/<str:\u0394>/', lambda r: None)
  249. match = p.resolve('hello/1/')
  250. self.assertEqual(match.kwargs, {'\u0394': '1'})
  251. @override_settings(ROOT_URLCONF='urlpatterns.path_dynamic_urls')
  252. class ConversionExceptionTests(SimpleTestCase):
  253. """How are errors in Converter.to_python() and to_url() handled?"""
  254. def test_resolve_value_error_means_no_match(self):
  255. @DynamicConverter.register_to_python
  256. def raises_value_error(value):
  257. raise ValueError()
  258. with self.assertRaises(Resolver404):
  259. resolve('/dynamic/abc/')
  260. def test_resolve_type_error_propagates(self):
  261. @DynamicConverter.register_to_python
  262. def raises_type_error(value):
  263. raise TypeError('This type error propagates.')
  264. with self.assertRaisesMessage(TypeError, 'This type error propagates.'):
  265. resolve('/dynamic/abc/')
  266. def test_reverse_value_error_means_no_match(self):
  267. @DynamicConverter.register_to_url
  268. def raises_value_error(value):
  269. raise ValueError
  270. with self.assertRaises(NoReverseMatch):
  271. reverse('dynamic', kwargs={'value': object()})
  272. def test_reverse_type_error_propagates(self):
  273. @DynamicConverter.register_to_url
  274. def raises_type_error(value):
  275. raise TypeError('This type error propagates.')
  276. with self.assertRaisesMessage(TypeError, 'This type error propagates.'):
  277. reverse('dynamic', kwargs={'value': object()})