Creating Test-Specific URL Patterns and View Functions in Django

2017-12-19 22:10 (7 years ago) ytyng

Until Django 1.9, it seems that the urls attribute was written in SimpleTestCase, but when reading the code:

def _urlconf_setup(self):
if hasattr(self, 'urls'):
warnings.warn(
"SimpleTestCase.urls is deprecated and will be removed in "
"Django 1.10. Use @override_settings(ROOT_URLCONF=...) "
"in %s instead." % self.__class__.__name__,
RemovedInDjango110Warning, stacklevel=2)
set_urlconf(None)
self._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = self.urls
clear_url_caches()

Since it was written as deprecated, I followed this:

@override_settings(ROOT_URLCONF=...) 

and it worked.

from django.conf.urls import url
from django.core.urlresolvers import reverse
from django.http import JsonResponse
from django.test import TestCase, override_settings

from lib.current_request import get_current_request


def current_request_view(request):
"""
View for checking the operation of current_request()
"""
current_request = get_current_request()

return JsonResponse({
'current_request_path': current_request.path,
'request_path': request.path,
})


urlpatterns = [
url(r'^current-request/$', current_request_view,
name='current_request_view')
]


class CurrentRequestTest(TestCase):
@override_settings(ROOT_URLCONF="lib.tests.test_current_request")
def test_current_request(self):
response = self.client.get(reverse('current_request_view'))
data = response.json()
self.assertEqual(data['current_request_path'], '/current-request/')
self.assertEqual(data['request_path'], '/current-request/')

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011