Here are the examples of the python api django.conf.settings.ROOT_URLCONF taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
126 Examples
0
Example 101
Project: Geotrek-admin Source File: update_permissions.py
def execute(self, *args, **options):
logger.info("Synchronize django permissions")
for app in get_apps():
create_permissions(app, [], int(options.get('verbosity', 1)))
logger.info("Done.")
logger.info("Synchronize mapentity permissions")
# Make sure apps are registered at this point
import_module(settings.ROOT_URLCONF)
# For all models registered, add missing bits
for model in registry.registry.keys():
create_mapentity_model_permissions(model)
logger.info("Done.")
logger.info("Synchronize geotrek permissions")
for content_type in ContentType.objects.all():
model = content_type.model_class()
if model and issubclass(model, BasePublishableMixin):
Permission.objects.get_or_create(
codename='publish_%s' % content_type.model,
name='Can publish %s' % content_type.name,
content_type=content_type)
logger.info("Done.")
0
Example 102
def startTest(self, test):
"""
When preparing test, check whether to make our database fresh
"""
test_case = get_test_case_class(test)
if issubclass(test_case, DjangoTestCase):
return
#####
### FIXME: It would be nice to separate handlings as plugins et al...but what
### about the context?
#####
from django.core import mail
from django.conf import settings
from django.db import transaction
test_case = get_test_case_class(test)
test_case_instance = get_test_case_instance(test)
mail.outbox = []
enable_test(test_case, 'django_plugin_started')
if hasattr(test_case_instance, 'is_skipped') and test_case_instance.is_skipped():
return
# clear URLs if needed
if hasattr(test_case, 'urls'):
test_case._old_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = test_case.urls
clear_url_caches()
#####
### Database handling follows
#####
if getattr_test(test, 'no_database_interaction', False):
# for true unittests, we can leave database handling for later,
# as unittests by definition do not interacts with database
return
# create test database if not already created
if not self.test_database_created:
self._create_test_databases()
# make self.transaction available
test_case.transaction = transaction
if getattr_test(test, 'database_single_transaction'):
transaction.enter_transaction_management()
transaction.managed(True)
self._prepare_tests_fixtures(test)
0
Example 103
def stopTest(self, test):
"""
After test is run, clear urlconf, caches and database
"""
test_case = get_test_case_class(test)
if issubclass(test_case, DjangoTestCase):
return
from django.db import transaction
from django.conf import settings
test_case = get_test_case_class(test)
test_case_instance = get_test_case_instance(test)
if hasattr(test_case_instance, 'is_skipped') and test_case_instance.is_skipped():
return
if hasattr(test_case, '_old_root_urlconf'):
settings.ROOT_URLCONF = test_case._old_root_urlconf
clear_url_caches()
flush_cache(test)
if getattr_test(test, 'no_database_interaction', False):
# for true unittests, we can leave database handling for later,
# as unittests by definition do not interacts with database
return
if getattr_test(test, 'database_single_transaction'):
transaction.rollback()
transaction.leave_transaction_management()
if getattr_test(test, "database_flush", True):
for db in self._get_tests_databases(getattr_test(test, 'multi_db')):
getattr(settings, "TEST_DATABASE_FLUSH_COMMAND", flush_database)(self, database=db)
0
Example 104
def technical_404_response(request, exception):
"Create a technical 404 error response. The exception should be the Http404."
try:
tried = exception.args[0]['tried']
except (IndexError, TypeError, KeyError):
tried = []
else:
if not tried:
# tried exists but is an empty list. The URLconf must've been empty.
return empty_urlconf(request)
t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
c = Context({
'root_urlconf': settings.ROOT_URLCONF,
'request_path': request.path_info[1:], # Trim leading slash
'urlpatterns': tried,
'reason': smart_str(exception, errors='replace'),
'request': request,
'settings': get_safe_settings(),
})
return HttpResponseNotFound(t.render(c), mimetype='text/html')
0
Example 105
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
from django.core import exceptions, urlresolvers
from django.conf import settings
try:
# Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
if hasattr(request, "urlconf"):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
# Complain if the view returned None (a common error).
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))
except http.Http404, e:
logger.warning('Not Found: %s' % request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
from django.views import debug
response = debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
response = callback(request, **param_dict)
except:
try:
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
except exceptions.PermissionDenied:
logger.warning('Forbidden (Permission denied): %s' % request.path,
extra={
'status_code': 403,
'request': request
})
response = http.HttpResponseForbidden('<h1>Permission denied</h1>')
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
finally:
# Reset URLconf for this thread on the way out for complete
# isolation of request.urlconf
urlresolvers.set_urlconf(None)
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
return response
0
Example 106
def get_urlpatterns(self):
"""Return url patterns."""
urlconf_module = importlib.import_module(settings.ROOT_URLCONF)
return urlconf_module.urlpatterns
0
Example 107
Project: philo Source File: nodes.py
def construct_url(self, subpath="/", request=None, with_domain=False, secure=False):
"""
This method will do its best to construct a URL based on the Node's location. If with_domain is True, that URL will include a domain and a protocol; if secure is True as well, the protocol will be https. The request will be used to construct a domain in cases where a call to :meth:`Site.objects.get_current` fails.
Node urls will not contain a trailing slash unless a subpath is provided which ends with a trailing slash. Subpaths are expected to begin with a slash, as if returned by :func:`django.core.urlresolvers.reverse`.
Because this method will be called frequently and will always try to reverse ``philo-root``, the results of that reversal will be cached by default. This can be disabled by setting :setting:`PHILO_CACHE_PHILO_ROOT` to ``False``.
:meth:`construct_url` may raise the following exceptions:
- :class:`NoReverseMatch` if "philo-root" is not reversable -- for example, if :mod:`philo.urls` is not included anywhere in your urlpatterns.
- :class:`Site.DoesNotExist <ObjectDoesNotExist>` if with_domain is True but no :class:`Site` or :class:`RequestSite` can be built.
- :class:`~philo.exceptions.AncestorDoesNotExist` if the root node of the site isn't an ancestor of the node constructing the URL.
:param string subpath: The subpath to be constructed beyond beyond the node's URL.
:param request: :class:`HttpRequest` instance. Will be used to construct a :class:`RequestSite` if :meth:`Site.objects.get_current` fails.
:param with_domain: Whether the constructed URL should include a domain name and protocol.
:param secure: Whether the protocol, if included, should be http:// or https://.
:returns: A constructed url for accessing the given subpath of the current node instance.
"""
# Try reversing philo-root first, since we can't do anything if that fails.
if CACHE_PHILO_ROOT:
key = "CACHE_PHILO_ROOT__" + settings.ROOT_URLCONF
root_url = cache.get(key)
if root_url is None:
root_url = reverse('philo-root')
cache.set(key, root_url)
else:
root_url = reverse('philo-root')
try:
current_site = Site.objects.get_current()
except Site.DoesNotExist:
if request is not None:
current_site = RequestSite(request)
elif with_domain:
# If they want a domain and we can't figure one out,
# best to reraise the error to let them know.
raise
else:
current_site = None
root = getattr(current_site, 'root_node', None)
path = self.get_path(root=root)
if current_site and with_domain:
domain = "http%s://%s" % (secure and "s" or "", current_site.domain)
else:
domain = ""
if not path or subpath == "/":
subpath = subpath[1:]
return '%s%s%s%s' % (domain, root_url, path, subpath)
0
Example 108
def setUp(self):
settings.ROOT_URLCONF = "jellyroll.urls.calendar"
0
Example 109
Project: django-mongonaut Source File: url_tests.py
def testURLResolver(self):
'''
Tests whether reverse function inside get_docuement_value can
correctly return a docuement_detail url when given a set of:
<docuement_name> <app_label> and <id>
Both <docuement_name> and <app_label> will contain dots, eg.
<docuement_name> : 'User.NewUser'
<app_label> : 'examples.blog.articles'
'''
urls_tmp = settings.ROOT_URLCONF
settings.ROOT_URLCONF = 'examples.blog.urls'
u = NewUser(email='[email protected]')
u.id=ObjectId('abcabcabcabc')
p = Post(author=u, title='Test')
p.id = ObjectId('abcabcabcabc')
match_found = True
try:
v = get_docuement_value(p, 'author')
except NoReverseMatch, e:
match_found = False
settings.ROOT_URLCONF = urls_tmp
self.assertEquals(match_found, True)
0
Example 110
Project: django-mongonaut Source File: url_tests.py
def testDetailViewRendering(self):
'''
Tries to render a detail view byt giving it data
from examples.blog. As <app_label> and <docuement_name>
may contain dots, it checks whether NoReverseMatch exception
was raised.
'''
self.req.user = DummyUser()
urls_tmp = settings.ROOT_URLCONF
settings.ROOT_URLCONF = 'examples.blog.urls'
self.view = DocuementDetailView.as_view()(
app_label='examples.blog.articles',
docuement_name='Post',
id=ObjectId('abcabcabcabc'),
request=self.req,
models=import_module('examples.blog.articles.models')
)
match_found = True
try:
self.view.render()
except NoReverseMatch, e:
match_found = False
settings.ROOT_URLCONF = urls_tmp
self.assertEquals(match_found, True)
0
Example 111
Project: django-mongonaut Source File: url_tests.py
def testUnicodeURLResolver(self):
'''
Similarly to testURLResolver, it tests whether get_docuement_value does not throw an exception.
This time, the value with unicode characters is provided.
'''
settings.ROOT_URLCONF = 'examples.blog.urls'
# Some unicode characters
email = u"ąćźżńłóśę@gmail.com"
u = NewUser(email=email)
u.id=ObjectId('abcabcabcabc')
p = Post(author=u, title='Test Post')
p.id = ObjectId('abcabcabcabc')
unicode_ok = False
try:
res = get_docuement_value(p, 'author')
unicode_ok = True
except UnicodeEncodeError, e:
pass
self.assertTrue(unicode_ok)
0
Example 112
def reload_urlconf(urlconf=None):
if urlconf is None:
urlconf = settings.ROOT_URLCONF
if urlconf in sys.modules:
reload(sys.modules[urlconf])
0
Example 113
Project: ANALYSE Source File: tests.py
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms')
@patch('courseware.views.log.warning')
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_PAID_COURSE_REGISTRATION': True})
def test_blocked_course_scenario(self, log_warning):
self.client.login(username="jack", password="test")
#create testing invoice 1
sale_invoice_1 = shoppingcart.models.Invoice.objects.create(
total_amount=1234.32, company_name='Test1', company_contact_name='Testw',
company_contact_email='[email protected]', customer_reference_number='2Fwe23S',
recipient_name='Testw_1', recipient_email='[email protected]', internal_reference="A",
course_id=self.course.id, is_valid=False
)
course_reg_code = shoppingcart.models.CourseRegistrationCode(code="abcde", course_id=self.course.id,
created_by=self.user, invoice=sale_invoice_1)
course_reg_code.save()
cart = shoppingcart.models.Order.get_cart_for_user(self.user)
shoppingcart.models.PaidCourseRegistration.add_to_order(cart, self.course.id)
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': course_reg_code.code})
self.assertEqual(resp.status_code, 200)
# freely enroll the user into course
resp = self.client.get(reverse('shoppingcart.views.register_courses'))
self.assertIn('success', resp.content)
response = self.client.get(reverse('dashboard'))
self.assertIn('You can no longer access this course because payment has not yet been received', response.content)
optout_object = Optout.objects.filter(user=self.user, course_id=self.course.id)
self.assertEqual(len(optout_object), 1)
# Direct link to course redirect to user dashboard
self.client.get(reverse('courseware', kwargs={"course_id": self.course.id.to_deprecated_string()}))
log_warning.assert_called_with(
u'User %s cannot access the course %s because payment has not yet been received', self.user, self.course.id.to_deprecated_string())
# Now re-validating the invoice
invoice = shoppingcart.models.Invoice.objects.get(id=sale_invoice_1.id)
invoice.is_valid = True
invoice.save()
response = self.client.get(reverse('dashboard'))
self.assertNotIn('You can no longer access this course because payment has not yet been received', response.content)
0
Example 114
@skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in LMS')
def test_password_change(self):
# Request a password change while logged in, simulating
# use of the password reset link from the account page
response = self._change_password()
self.assertEqual(response.status_code, 200)
# Check that an email was sent
self.assertEqual(len(mail.outbox), 1)
# Retrieve the activation link from the email body
email_body = mail.outbox[0].body
result = re.search('(?P<url>https?://[^\s]+)', email_body)
self.assertIsNot(result, None)
activation_link = result.group('url')
# Visit the activation link
response = self.client.get(activation_link)
self.assertEqual(response.status_code, 200)
# Submit a new password and follow the redirect to the success page
response = self.client.post(
activation_link,
# These keys are from the form on the current password reset confirmation page.
{'new_password1': self.NEW_PASSWORD, 'new_password2': self.NEW_PASSWORD},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Your password has been set.")
# Log the user out to clear session data
self.client.logout()
# Verify that the new password can be used to log in
result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD)
self.assertTrue(result)
# Try reusing the activation link to change the password again
response = self.client.post(
activation_link,
{'new_password1': self.OLD_PASSWORD, 'new_password2': self.OLD_PASSWORD},
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertContains(response, "The password reset link was invalid, possibly because the link has already been used.")
self.client.logout()
# Verify that the old password cannot be used to log in
result = self.client.login(username=self.USERNAME, password=self.OLD_PASSWORD)
self.assertFalse(result)
# Verify that the new password continues to be valid
result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD)
self.assertTrue(result)
0
Example 115
Project: localwiki-backend-server Source File: cards_tags.py
def render_page_card(context, page):
from maps.widgets import map_options_for_region
cache = get_cache('long-living')
request = context['request']
card = cache.get('card:%s,%s' % (get_urlconf() or settings.ROOT_URLCONF, page.id))
if card:
return card
_file, _map = None, None
# Try and get a useful image
_file = page.get_highlight_image()
# Otherwise, try and get a map
if not _file and hasattr(page, 'mapdata'):
olwidget_options.update(map_options_for_region(page.region))
_map = InfoMap(
[(page.mapdata.geom, '')],
options=olwidget_options
).render(None, None, {'id': 'map_page_id_%s' % page.id})
card = render_to_string('cards/base.html', {
'obj': page,
'file': _file.file if _file else None,
'map': _map,
'title': page.name,
'content': page.content,
})
cache.set('card:%s,%s' % (get_urlconf() or settings.ROOT_URLCONF, page.id), card)
return card
0
Example 116
def render(self, context):
from django.core.urlresolvers import reverse, NoReverseMatch
args = [arg.resolve(context) for arg in self.args]
kwargs = dict([(smart_text(k, 'ascii'), v.resolve(context))
for k, v in self.kwargs.items()])
view_name = self.view_name.resolve(context)
if not view_name:
raise NoReverseMatch("'url' requires a non-empty first argument. "
"The syntax changed in Django 1.5, see the docs.")
# Try to look up the URL twice: once given the view name, and again
# relative to what we guess is the "main" app. If they both fail,
# re-raise the NoReverseMatch unless we're using the
# {% url ... as var %} construct in which case return nothing.
url = ''
try:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app, urlconf=self.urlconf)
except NoReverseMatch as e:
try:
url = reverse(view_name, args=args, kwargs=kwargs, current_app=context.current_app)
except NoReverseMatch:
if self.urlconf != settings.ROOT_URLCONF:
# Re-try to match on the base urlconf instead, and render as an absolute URL.
try:
host = settings.DEFAULT_HOST
host_args, host_kwargs = (), {}
return HostURLNode(host, self.view_name, host_args, host_kwargs, self.args, self.original_kwargs, self.asvar).render(context)
except:
pass
if self.asvar is None:
# Re-raise the original exception, not the one with
# the path relative to the project. This makes a
# better error message.
raise e
if self.asvar:
context[self.asvar] = url
return ''
else:
return url
0
Example 117
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
from django.core import exceptions, urlresolvers
from django.conf import settings
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
return response
# Get urlconf from request object, if available. Otherwise use default.
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
callback, callback_args, callback_kwargs = resolver.resolve(
request.path_info)
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
return response
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
return response
raise
# Complain if the view returned None (a common error).
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
return response
except http.Http404, e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)
else:
try:
callback, param_dict = resolver.resolve404()
return callback(request, **param_dict)
except:
return self.handle_uncaught_exception(request, resolver, sys.exc_info())
except exceptions.PermissionDenied:
return http.HttpResponseForbidden('<h1>Permission denied</h1>')
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else, including SuspiciousOperation, etc.
# Get the exception info now, in case another exception is thrown later.
exc_info = sys.exc_info()
receivers = dispatcher.send(signal=signals.got_request_exception, request=request)
return self.handle_uncaught_exception(request, resolver, exc_info)
0
Example 118
def process_request(self, request):
__traceback_hide__ = True
if self.show_toolbar(request):
urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
if isinstance(urlconf, basestring):
urlconf = import_module(getattr(request, 'urlconf', settings.ROOT_URLCONF))
if urlconf not in self._urlconfs:
new_urlconf = imp.new_module('urlconf')
new_urlconf.urlpatterns = debug_toolbar.urls.urlpatterns + \
urlconf.urlpatterns
if hasattr(urlconf, 'handler404'):
new_urlconf.handler404 = urlconf.handler404
if hasattr(urlconf, 'handler500'):
new_urlconf.handler500 = urlconf.handler500
self._urlconfs[urlconf] = new_urlconf
request.urlconf = self._urlconfs[urlconf]
toolbar = DebugToolbar(request)
for panel in toolbar.panels:
panel.process_request(request)
self.__class__.debug_toolbars[thread.get_ident()] = toolbar
0
Example 119
def get_response(self, request):
"Returns an HttpResponse object for the given HttpRequest"
from django.core import exceptions, urlresolvers
from django.core.mail import mail_admins
from django.conf import settings
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
return response
# Get urlconf from request object, if available. Otherwise use default.
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
try:
callback, callback_args, callback_kwargs = resolver.resolve(request.path)
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
return response
try:
response = callback(request, *callback_args, **callback_kwargs)
except Exception, e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
return response
raise
# Complain if the view returned None (a common error).
if response is None:
try:
view_name = callback.func_name # If it's a function
except AttributeError:
view_name = callback.__class__.__name__ + '.__call__' # If it's a class
raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
return response
except http.Http404, e:
if settings.DEBUG:
from django.views import debug
return debug.technical_404_response(request, e)
else:
callback, param_dict = resolver.resolve404()
return callback(request, **param_dict)
except exceptions.PermissionDenied:
return http.HttpResponseForbidden('<h1>Permission denied</h1>')
except SystemExit:
pass # See http://code.djangoproject.com/ticket/1023
except: # Handle everything else, including SuspiciousOperation, etc.
if settings.DEBUG:
from django.views import debug
return debug.technical_500_response(request, *sys.exc_info())
else:
# Get the exception info now, in case another exception is thrown later.
exc_info = sys.exc_info()
receivers = dispatcher.send(signal=signals.got_request_exception)
# When DEBUG is False, send an error message to the admins.
subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
try:
request_repr = repr(request)
except:
request_repr = "Request repr() unavailable"
message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
mail_admins(subject, message, fail_silently=True)
# Return an HttpResponse that displays a friendly error message.
callback, param_dict = resolver.resolve500()
return callback(request, **param_dict)
0
Example 120
def afterTest(self, test):
"""
Clean up any changes to the test database.
"""
# Restore transaction support on tests
from django.conf import settings
from django.db import connections
from django.core import mail
from django.core.urlresolvers import clear_url_caches
mail.outbox = []
if hasattr(test.context, '_nosedjango_root_urlconf'):
settings.ROOT_URLCONF = test.context._nosedjango_root_urlconf
clear_url_caches()
use_transaction_isolation = self.should_use_transaction_isolation(
test, settings)
if use_transaction_isolation:
self.restore_transaction_support()
logger.debug("Rolling back")
self.exit_atomics()
self.restore_autocommit()
self.rollback()
if self.transaction_is_managed():
self.transaction.leave_transaction_management()
# If connection is not closed Postgres can go wild with
# character encodings.
for connection in connections.all():
connection.close()
else:
# Have to clear the db even if we're using django because django
# doesn't properly flush the database after a test. It relies on
# flushing before a test, so we want to avoid the case where a
# django test doesn't flush and then a normal test runs, because it
# will expect the db to already be flushed
self._flush_db()
self._loaded_test_fixtures = []
self.call_plugins_method('afterRollback', settings)
0
Example 121
Project: nosedjango Source File: nosedjango.py
def beforeTest(self, test):
"""
Load any database fixtures, set up any test url configurations and
prepare for using transactions for database rollback if possible.
"""
if not self.settings_path:
# short circuit if no settings file can be found
return
from django.contrib.sites.models import Site
from django.contrib.contenttypes.models import ContentType
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.conf import settings
use_transaction_isolation = self.should_use_transaction_isolation(
test, settings)
if use_transaction_isolation:
self.call_plugins_method(
'beforeTransactionManagement',
settings,
test,
)
self.transaction.enter_transaction_management()
self.transaction.managed(True)
self.restore_transaction_support()
self.enable_autocommit()
self.disable_transaction_support()
Site.objects.clear_cache()
# Otherwise django.contrib.auth.Permissions will depend on deleted
# ContentTypes
ContentType.objects.clear_cache()
if use_transaction_isolation:
self.call_plugins_method(
'afterTransactionManagement',
settings,
test,
)
self.call_plugins_method('beforeFixtureLoad', settings, test)
if isinstance(test, nose.case.Test):
# Mirrors django.test.testcases:TestCase
fixtures_to_load = getattr(test.context, 'fixtures', [])
if fixtures_to_load is None:
fixtures_to_load = []
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
ordered_fixtures = sorted(fixtures_to_load)
if ordered_fixtures != self._loaded_test_fixtures:
# Only clear + load the fixtures if they're not already
# loaded
# Flush previous fixtures
if use_transaction_isolation:
self.restore_transaction_support()
self._flush_db()
# Load the new fixtures
logger.debug("Loading fixtures: %s", fixtures_to_load)
if fixtures_to_load:
commit = True
if use_transaction_isolation:
commit = False
call_command(
'loaddata',
*test.context.fixtures,
**{'verbosity': 0, 'commit': commit}
)
if use_transaction_isolation:
self.restore_transaction_support()
self.commit()
self.disable_transaction_support()
self._num_fixture_loads += 1
self._loaded_test_fixtures = ordered_fixtures
self.call_plugins_method('afterFixtureLoad', settings, test)
self.call_plugins_method('beforeUrlConfLoad', settings, test)
if isinstance(test, nose.case.Test) and \
hasattr(test.context, 'urls'):
# We have to use this slightly awkward syntax due to the fact
# that we're using *args and **kwargs together.
test.context._nosedjango_root_urlconf = settings.ROOT_URLCONF
settings.ROOT_URLCONF = test.context.urls
clear_url_caches()
self.call_plugins_method('afterUrlConfLoad', settings, test)
if use_transaction_isolation:
self.restore_transaction_support()
self.enter_atomics()
self.disable_transaction_support()
if hasattr(test.context, 'client_class'):
test.context.client = test.context.client_class()
0
Example 122
def test_root_urlconf_is_set(self):
from django.conf import settings
self.assertEqual(settings.ROOT_URLCONF, 'foo')
0
Example 123
Project: nosedjango Source File: test_urlconf.py
def test_root_urlconf_is_default(self):
from django.conf import settings
self.assertEqual(settings.ROOT_URLCONF, DEFAULT_ROOT_URLCONF)
0
Example 124
def test_root_urlconf_is_set(self):
from django.conf import settings
self.assertEqual(settings.ROOT_URLCONF, 'bar')
0
Example 125
Project: gro-api Source File: patch_resolvers.py
def new_get_response(self, request):
# Setup default url resolver for this thread, this code is outside
# the try/except so we don't get a spurious "unbound local
# variable" exception in the event an exception is raised before
# resolver is set
urlconf = settings.ROOT_URLCONF
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.get_resolver(urlconf)
try:
response = None
# Apply request middleware
for middleware_method in self._request_middleware:
response = middleware_method(request)
if response:
break
if response is None:
if hasattr(request, 'urlconf'):
# Reset url resolver with a custom urlconf.
urlconf = request.urlconf
urlresolvers.set_urlconf(urlconf)
resolver = urlresolvers.get_resolver(urlconf)
resolver_match = resolver.resolve(request.path_info)
callback, callback_args, callback_kwargs = resolver_match
request.resolver_match = resolver_match
# Apply view middleware
for middleware_method in self._view_middleware:
response = middleware_method(request, callback, callback_args, callback_kwargs)
if response:
break
if response is None:
wrapped_callback = self.make_view_atomic(callback)
try:
response = wrapped_callback(request, *callback_args, **callback_kwargs)
except Exception as e:
# If the view raised an exception, run it through exception
# middleware, and if the exception middleware returns a
# response, use that. Otherwise, reraise the exception.
for middleware_method in self._exception_middleware:
response = middleware_method(request, e)
if response:
break
if response is None:
raise
# Complain if the view returned None (a common error).
if response is None:
if isinstance(callback, types.FunctionType): # FBV
view_name = callback.__name__
else: # CBV
view_name = callback.__class__.__name__ + '.__call__'
raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
% (callback.__module__, view_name))
# If the response supports deferred rendering, apply template
# response middleware and then render the response
if hasattr(response, 'render') and callable(response.render):
for middleware_method in self._template_response_middleware:
response = middleware_method(request, response)
# Complain if the template response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_template_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
response = response.render()
except http.Http404 as e:
django_handlers_logger.warning('Not Found: %s', request.path,
extra={
'status_code': 404,
'request': request
})
if settings.DEBUG:
response = debug.technical_404_response(request, e)
else:
response = self.get_exception_response(request, resolver, 404)
except PermissionDenied:
django_handlers_logger.warning(
'Forbidden (Permission denied): %s', request.path,
extra={
'status_code': 403,
'request': request
})
response = self.get_exception_response(request, resolver, 403)
except MultiPartParserError:
django_handlers_logger.warning(
'Bad request (Unable to parse request body): %s', request.path,
extra={
'status_code': 400,
'request': request
})
response = self.get_exception_response(request, resolver, 400)
except SuspiciousOperation as e:
# The request logger receives events for any problematic request
# The security logger receives events for all SuspiciousOperations
security_logger = logging.getLogger('django.security.%s' %
e.__class__.__name__)
security_logger.error(
force_text(e),
extra={
'status_code': 400,
'request': request
})
if settings.DEBUG:
return debug.technical_500_response(request, *sys.exc_info(), status_code=400)
response = self.get_exception_response(request, resolver, 400)
except SystemExit:
# Allow sys.exit() to actually exit. See tickets #1023 and #4701
raise
except: # Handle everything else.
# Get the exception info now, in case another exception is thrown later.
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
try:
# Apply response middleware, regardless of the response
for middleware_method in self._response_middleware:
response = middleware_method(request, response)
# Complain if the response middleware returned None (a common error).
if response is None:
raise ValueError(
"%s.process_response didn't return an "
"HttpResponse object. It returned None instead."
% (middleware_method.__self__.__class__.__name__))
response = self.apply_response_fixes(request, response)
except: # Any exception should be gathered and handled
signals.got_request_exception.send(sender=self.__class__, request=request)
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
response._closable_objects.append(request)
return response
0
Example 126
def __init__(self, apps=None):
root_urlconf = importlib.import_module(settings.ROOT_URLCONF)
endpoints = self.get_all_view_names(root_urlconf.urlpatterns)
self.build_docs_tree(endpoints)
self.apps = apps