| 1 |
from django.shortcuts import resolve_url |
| 2 |
from django.test import SimpleTestCase, override_settings |
| 3 |
from django.urls import NoReverseMatch, reverse_lazy |
| 4 |
|
| 5 |
from .models import UnimportantThing |
| 6 |
from .urls import some_view |
| 7 |
|
| 8 |
|
| 9 |
@override_settings(ROOT_URLCONF="resolve_url.urls") |
| 10 |
class ResolveUrlTests(SimpleTestCase): |
| 11 |
""" |
| 12 |
Tests for the resolve_url() function. |
| 13 |
""" |
| 14 |
|
| 15 |
def test_url_path(self): |
| 16 |
""" |
| 17 |
Passing a URL path to resolve_url() results in the same url. |
| 18 |
""" |
| 19 |
self.assertEqual("/something/", resolve_url("/something/")) |
| 20 |
|
| 21 |
def test_relative_path(self): |
| 22 |
""" |
| 23 |
Passing a relative URL path to resolve_url() results in the same url. |
| 24 |
""" |
| 25 |
self.assertEqual("../", resolve_url("../")) |
| 26 |
self.assertEqual("../relative/", resolve_url("../relative/")) |
| 27 |
self.assertEqual("./", resolve_url("./")) |
| 28 |
self.assertEqual("./relative/", resolve_url("./relative/")) |
| 29 |
|
| 30 |
def test_full_url(self): |
| 31 |
""" |
| 32 |
Passing a full URL to resolve_url() results in the same url. |
| 33 |
""" |
| 34 |
url = "http://example.com/" |
| 35 |
self.assertEqual(url, resolve_url(url)) |
| 36 |
|
| 37 |
def test_model(self): |
| 38 |
""" |
| 39 |
Passing a model to resolve_url() results in get_absolute_url() being |
| 40 |
called on that model instance. |
| 41 |
""" |
| 42 |
m = UnimportantThing(importance=1) |
| 43 |
self.assertEqual(m.get_absolute_url(), resolve_url(m)) |
| 44 |
|
| 45 |
def test_view_function(self): |
| 46 |
""" |
| 47 |
Passing a view function to resolve_url() results in the URL path |
| 48 |
mapping to that view name. |
| 49 |
""" |
| 50 |
resolved_url = resolve_url(some_view) |
| 51 |
self.assertEqual("/some-url/", resolved_url) |
| 52 |
|
| 53 |
def test_lazy_reverse(self): |
| 54 |
""" |
| 55 |
Passing the result of reverse_lazy is resolved to a real URL |
| 56 |
string. |
| 57 |
""" |
| 58 |
resolved_url = resolve_url(reverse_lazy("some-view")) |
| 59 |
self.assertIsInstance(resolved_url, str) |
| 60 |
self.assertEqual("/some-url/", resolved_url) |
| 61 |
|
| 62 |
def test_valid_view_name(self): |
| 63 |
""" |
| 64 |
Passing a view name to resolve_url() results in the URL path mapping |
| 65 |
to that view. |
| 66 |
""" |
| 67 |
resolved_url = resolve_url("some-view") |
| 68 |
self.assertEqual("/some-url/", resolved_url) |
| 69 |
|
| 70 |
def test_domain(self): |
| 71 |
""" |
| 72 |
Passing a domain to resolve_url() returns the same domain. |
| 73 |
""" |
| 74 |
self.assertEqual(resolve_url("example.com"), "example.com") |
| 75 |
|
| 76 |
def test_non_view_callable_raises_no_reverse_match(self): |
| 77 |
""" |
| 78 |
Passing a non-view callable into resolve_url() raises a |
| 79 |
NoReverseMatch exception. |
| 80 |
""" |
| 81 |
with self.assertRaises(NoReverseMatch): |
| 82 |
resolve_url(lambda: "asdf") |