Ticket #16605: 16605-with-tests-2.diff

File 16605-with-tests-2.diff, 7.4 KB (added by Ramiro Morales, 13 years ago)

Another interation of the patch, with addition of a helper function as suggested by Russell

  • django/test/client.py

    diff --git a/django/test/client.py b/django/test/client.py
    a b  
    1313
    1414from django.conf import settings
    1515from django.contrib.auth import authenticate, login
     16from django.contrib.sessions.middleware import SessionMiddleware
    1617from django.core.handlers.base import BaseHandler
    1718from django.core.handlers.wsgi import WSGIRequest
    1819from django.core.signals import got_request_exception
     
    2425from django.utils.http import urlencode
    2526from django.utils.importlib import import_module
    2627from django.utils.itercompat import is_iterable
     28from django.utils.module_loading import issubclass_by_name
    2729from django.db import close_connection
    2830from django.test.utils import ContextList
    2931
     
    497499        not available.
    498500        """
    499501        user = authenticate(**credentials)
    500         if user and user.is_active \
    501                 and 'django.contrib.sessions.middleware.SessionMiddleware' in settings.MIDDLEWARE_CLASSES:
     502        sessions_enabled = False
     503        if user and user.is_active:
     504            for middleware in settings.MIDDLEWARE_CLASSES:
     505                sessions_enabled = issubclass_by_name(middleware, SessionMiddleware)
     506                if sessions_enabled:
     507                    break
     508        if sessions_enabled:
    502509            engine = import_module(settings.SESSION_ENGINE)
    503510
    504511            # Create a fake request to store login details.
  • django/utils/module_loading.py

    diff --git a/django/utils/module_loading.py b/django/utils/module_loading.py
    a b  
    22import os
    33import sys
    44
     5from django.utils.importlib import import_module
     6
    57
    68def module_has_submodule(package, module_name):
    79    """See if 'module' is in 'package'."""
     
    6769    else:
    6870        # Exhausted the search, so the module cannot be found.
    6971        return False
     72
     73def issubclass_by_name(symbol_name, klass):
     74    """
     75    Verify if possibly dotted, in string form :param symbol_name: is a
     76    subclass of :param klass:.
     77
     78    Example:
     79
     80    >>> issubclass_by_name('django.utils.datastructures.SortedDict', dict)
     81    True
     82    """
     83    try:
     84        mod, dot, klass_name = symbol_name.rpartition('.')
     85        mod = import_module(mod)
     86        subclass = getattr(mod, klass_name, None)
     87        if subclass is None:
     88            return False
     89        return issubclass(subclass, klass)
     90    except ImportError:
     91        return False
  • new file tests/regressiontests/test_client_regress/middleware.py

    diff --git a/tests/regressiontests/test_client_regress/middleware.py b/tests/regressiontests/test_client_regress/middleware.py
    new file mode 100644
    - +  
     1from django.contrib.sessions.middleware import SessionMiddleware
     2
     3
     4class CustomizedDjangoSessionMiddleware(SessionMiddleware):
     5    pass
     6
     7
     8class ReallyCustomSessionMiddleware(object):
     9    pass
  • tests/regressiontests/test_client_regress/models.py

    diff --git a/tests/regressiontests/test_client_regress/models.py b/tests/regressiontests/test_client_regress/models.py
    a b  
    22"""
    33Regression tests for the Test Client, especially the customized assertions.
    44"""
     5from __future__ import absolute_import
     6
    57import os
    68import warnings
    79
     
    1719from django.template.response import SimpleTemplateResponse
    1820from django.http import HttpResponse
    1921
     22from . import middleware
     23
     24CUSTOM_SESSION_MIDDLEWARE1 = '%s.CustomizedDjangoSessionMiddleware' % middleware.__name__
     25CUSTOM_SESSION_MIDDLEWARE2 = '%s.ReallyCustomSessionMiddleware' % middleware.__name__
    2026
    2127class AssertContainsTests(TestCase):
    2228    def setUp(self):
     
    564570        self.assertEqual(response.context['user'].username, 'testclient')
    565571
    566572
    567 class NoSessionsAppInstalled(SessionEngineTests):
    568     """#7836 - Test client can exercise sessions even when 'django.contrib.sessions' isn't installed."""
     573class SessionMiddlewareTests(TestCase):
     574    fixtures = ['testdata']
    569575
    570576    # Remove the 'session' contrib app from INSTALLED_APPS
    571577    @override_settings(INSTALLED_APPS=tuple(filter(lambda a: a!='django.contrib.sessions', settings.INSTALLED_APPS)))
    572     def test_session(self):
     578    def test_no_session_app(self):
     579        """Test client can exercise sessions even when 'django.contrib.sessions' isn't installed (#7836)."""
    573580        # This request sets a session variable.
    574581        response = self.client.get('/test_client_regress/set_session/')
    575582        self.assertEqual(response.status_code, 200)
    576583        self.assertEqual(self.client.session['session_var'], 'YES')
    577584
     585    # Use a custom session middleware that inherits from Django's
     586    @override_settings(
     587        MIDDLEWARE_CLASSES=map(
     588            lambda m: m if m!='django.contrib.sessions.middleware.SessionMiddleware' else CUSTOM_SESSION_MIDDLEWARE1,
     589            settings.MIDDLEWARE_CLASSES
     590        )
     591    )
     592    def test_subclassed_session_middleware(self):
     593        """Test client can login when a subclass of Django SessionMiddleware is in use (#16605)."""
     594        login = self.client.login(username='testclient', password='password')
     595        self.assertTrue(login, 'Could not log in')
     596
     597    # Use a custom session middleware
     598    @override_settings(
     599        MIDDLEWARE_CLASSES=map(
     600            lambda m: m if m!='django.contrib.sessions.middleware.SessionMiddleware' else CUSTOM_SESSION_MIDDLEWARE2,
     601            settings.MIDDLEWARE_CLASSES
     602        )
     603    )
     604    def test_custom_session_middleware(self):
     605        """Test client can login when a custom session middleware is in use."""
     606        login = self.client.login(username='testclient', password='password')
     607        self.assertTrue(login, 'Could not log in')
     608
    578609
    579610class URLEscapingTests(TestCase):
    580611    def test_simple_argument_get(self):
  • tests/regressiontests/utils/module_loading.py

    diff --git a/tests/regressiontests/utils/module_loading.py b/tests/regressiontests/utils/module_loading.py
    a b  
    55
    66from django.utils import unittest
    77from django.utils.importlib import import_module
    8 from django.utils.module_loading import module_has_submodule
     8from django.utils.module_loading import module_has_submodule, issubclass_by_name
    99
    1010
    1111class DefaultLoader(unittest.TestCase):
     
    154154    def tearDown(self):
    155155        super(CustomLoader, self).tearDown()
    156156        sys.path_hooks.pop(0)
     157
     158
     159class IssubclassByNameTests(unittest.TestCase):
     160    def test_success(self):
     161        self.assertTrue(issubclass_by_name('django.utils.datastructures.SortedDict', dict))
     162
     163    def test_failure(self):
     164        self.assertFalse(issubclass_by_name('django.utils.datastructures.SortedDict', str))
     165
     166    def test_import_failure_returns_false(self):
     167        self.assertFalse(issubclass_by_name('i.dont.exist.SortedDict', str))
     168
     169    def test_bogus_symbol_name_returns_false(self):
     170        self.assertFalse(issubclass_by_name('django.utils.module_loading.IDontExist', str))
  • tests/regressiontests/utils/tests.py

    diff --git a/tests/regressiontests/utils/tests.py b/tests/regressiontests/utils/tests.py
    a b  
    55
    66from .dateformat import DateFormatTests
    77from .feedgenerator import FeedgeneratorTest
    8 from .module_loading import DefaultLoader, EggLoader, CustomLoader
     8from .module_loading import DefaultLoader, EggLoader, CustomLoader, IssubclassByNameTests
    99from .termcolors import TermColorTests
    1010from .html import TestUtilsHtml
    1111from .http import TestUtilsHttp
Back to Top