django1/django/test/utils.py

586 lines
19 KiB
Python
Raw Normal View History

from contextlib import contextmanager
import logging
import re
import sys
import time
from unittest import skipUnless
import warnings
from functools import wraps
from xml.dom.minidom import parseString, Node
from django.apps import apps
from django.conf import settings, UserSettingsHolder
from django.core import mail
from django.core.signals import request_started
from django.db import reset_queries
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
from django.http import request
from django.template import Template, loader, TemplateDoesNotExist
from django.template.loaders import cached
from django.test.signals import template_rendered, setting_changed
from django.utils import six
2014-03-23 04:08:59 +08:00
from django.utils.deprecation import RemovedInDjango19Warning, RemovedInDjango20Warning
from django.utils.encoding import force_str
from django.utils.translation import deactivate
__all__ = (
'Approximate', 'ContextList', 'get_runner',
'modify_settings', 'override_settings',
'requires_tz_support',
'setup_test_environment', 'teardown_test_environment',
)
RESTORE_LOADERS_ATTR = '_original_template_source_loaders'
TZ_SUPPORT = hasattr(time, 'tzset')
class Approximate(object):
def __init__(self, val, places=7):
self.val = val
self.places = places
def __repr__(self):
return repr(self.val)
def __eq__(self, other):
if self.val == other:
return True
Fixed #3011 -- Added swappable auth.User models. Thanks to the many people that contributed to the development and review of this patch, including (but not limited to) Jacob Kaplan-Moss, Anssi Kääriäinen, Ramiro Morales, Preston Holmes, Josh Ourisman, Thomas Sutton, and Roger Barnes, as well as the many, many people who have contributed to the design discussion around this ticket over many years. Squashed commit of the following: commit d84749a0f034a0a6906d20df047086b1219040d0 Merge: 531e771 7c11b1a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 18:37:04 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 531e7715da545f930c49919a19e954d41c59b446 Merge: 29d1abb 1f84b04 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 07:09:23 2012 +0800 Merged recent trunk changes. commit 29d1abbe351fd5da855fe5ce09e24227d90ddc91 Merge: 8a527dd 54c81a1 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:49:46 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8a527dda13c9bec955b1f7e8db5822d1d9b32a01 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:48:05 2012 +0800 Ensure sequences are reset correctly in the presence of swapped models. commit e2b6e22f298eb986d74d28b8d9906f37f5ff8eb8 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 17:53:05 2012 +0800 Modifications to the handling and docs for auth forms. commit 98aba856b534620aea9091f824b442b47d2fdb3c Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 15:28:57 2012 +0800 Improved error handling and docs for get_user_model() commit 0229209c844f06dfeb33b0b8eeec000c127695b6 Merge: 6494bf9 8599f64 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 14:50:11 2012 +0800 Merged recent Django trunk changes. commit 6494bf91f2ddaaabec3ec017f2e3131937c35517 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 21:38:44 2012 +0800 Improved validation of swappable model settings. commit 5a04cde342cc860384eb844cfda5af55204564ad Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 07:15:14 2012 +0800 Removed some unused imports. commit ffd535e4136dc54f084b6ac467e81444696e1c8a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:31:28 2012 +0800 Corrected attribute access on for get_by_natural_key commit 913e1ac84c3d9c7c58a9b3bdbbb15ebccd8a8c0a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:12:34 2012 +0800 Added test for proxy model safeguards on swappable models. commit 280bf19e94d0d534d0e51bae485c1842558f4ff4 Merge: dbb3900 935a863 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:16:49 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit dbb3900775a99df8b6cb1d7063cf364eab55621a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:09:27 2012 +0800 Fixes for Python 3 compatibility. commit dfd72131d8664615e245aa0f95b82604ba6b3821 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:54:30 2012 +0800 Added protection against proxying swapped models. commit abcb027190e53613e7f1734e77ee185b2587de31 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:11:10 2012 +0800 Cleanup and documentation of AbstractUser base class. commit a9491a87763e307f0eb0dc246f54ac865a6ffb34 Merge: fd8bb4e 08bcb4a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:46:49 2012 +0800 Merge commit '08bcb4aec1ed154cefc631b8510ee13e9af0c19d' into t3011 commit fd8bb4e3e498a92d7a8b340f0684d5f088aa4c92 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:20:14 2012 +0800 Documentation improvements coming from community review. commit b550a6d06d016ab6a0198c4cb2dffe9cceabe8a5 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:52:47 2012 +0800 Refactored skipIfCustomUser into the contrib.auth tests. commit 52a02f11107c3f0d711742b8ca65b75175b79d6a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:46:10 2012 +0800 Refactored common 'get' pattern into manager method. commit b441a6bbc7d6065175715cb09316b9f13268171b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:41:33 2012 +0800 Added note about backwards incompatible change to admin login messages. commit 08bcb4aec1ed154cefc631b8510ee13e9af0c19d Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:33 2012 +0300 Splitted User to AbstractUser and User commit d9f5e5addbad5e1a01f67e7358e4f5091c3cad81 Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:02 2012 +0300 Reworked REQUIRED_FIELDS + create_user() interaction commit 579f152e4a6e06671e1ac1e59e2b43cf4d764bf4 Merge: 9184972 93e6733 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:37 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 918497218c58227f5032873ff97261627b2ceab2 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:19 2012 +0800 Deprecate AUTH_PROFILE_MODULE and get_profile(). commit 334cdfc1bb6a6794791497cdefda843bca2ea57a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:00:12 2012 +0800 Added release notes for new swappable User feature. commit 5d7bb22e8d913b51aba1c3360e7af8b01b6c0ab6 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 19:59:49 2012 +0800 Ensure swapped models can't be queried. commit 57ac6e3d32605a67581e875b37ec5b2284711a32 Merge: f2ec915 abfba3b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 14:31:54 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit f2ec915b20f81c8afeaa3df25f80689712f720f8 Merge: 1952656 5e99a3d Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:29:51 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 19526563b54fa300785c49cfb625c0c6158ced67 Merge: 2c5e833 c4aa26a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:22:26 2012 +0800 Merge recent changes from master. commit 2c5e833a30bef4305d55eacc0703533152f5c427 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 07:53:46 2012 +0800 Corrected admin_views tests following removal of the email fallback on admin logins. commit 20d1892491839d6ef21f37db4ca136935c2076bf Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 01:00:37 2012 +0800 Added conditional skips for all tests dependent on the default User model commit 40ea8b888284775481fc1eaadeff267dbd7e3dfa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:47:02 2012 +0800 Added documentation for REQUIRED_FIELDS in custom auth. commit e6aaf659708cf6491f5485d3edfa616cb9214cc0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:20:02 2012 +0800 Added first draft of custom User docs. Thanks to Greg Turner for the initial text. commit 75118bd242eec87649da2859e8c50a199a8a1dca Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 11:17:26 2012 +0800 Admin app should not allow username discovery The admin app login form should not allow users to discover the username associated with an email address. commit d088b3af58dad7449fc58493193a327725c57c22 Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 10:32:13 2012 +0800 Admin app login form should use swapped user model commit 7e82e83d67ee0871a72e1a3a723afdd214fcefc3 Merge: e29c010 39aa890 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Fri Sep 7 23:45:03 2012 +0800 Merged master changes. commit e29c010beb96ca07697c4e3e0c0d5d3ffdc4c0a3 Merge: 8e3fd70 30bdf22 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:12:57 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8e3fd703d02c31a4c3ac9f51f5011d03c0bd47f6 Merge: 507bb50 26e0ba0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:09:09 2012 +0800 Merged recent changes from trunk. commit 507bb50a9291bfcdcfa1198f9fea21d4e3b1e762 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:41:37 2012 +0800 Modified auth app so that login with alternate auth app is possible. commit dabe3628362ab7a4a6c9686dd874803baa997eaa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:10:51 2012 +0800 Modified auth management commands to handle custom user definitions. commit 7cc0baf89d490c92ef3f1dc909b8090191a1294b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 14:17:28 2012 +0800 Added model Meta option for swappable models, and made auth.User a swappable model
2012-09-26 18:48:09 +08:00
return round(abs(self.val - other), self.places) == 0
class ContextList(list):
"""A wrapper that provides direct key access to context items contained
in a list of context objects.
"""
def __getitem__(self, key):
if isinstance(key, six.string_types):
for subcontext in self:
if key in subcontext:
return subcontext[key]
raise KeyError(key)
else:
return super(ContextList, self).__getitem__(key)
def __contains__(self, key):
try:
Fixed #3011 -- Added swappable auth.User models. Thanks to the many people that contributed to the development and review of this patch, including (but not limited to) Jacob Kaplan-Moss, Anssi Kääriäinen, Ramiro Morales, Preston Holmes, Josh Ourisman, Thomas Sutton, and Roger Barnes, as well as the many, many people who have contributed to the design discussion around this ticket over many years. Squashed commit of the following: commit d84749a0f034a0a6906d20df047086b1219040d0 Merge: 531e771 7c11b1a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 18:37:04 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 531e7715da545f930c49919a19e954d41c59b446 Merge: 29d1abb 1f84b04 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 07:09:23 2012 +0800 Merged recent trunk changes. commit 29d1abbe351fd5da855fe5ce09e24227d90ddc91 Merge: 8a527dd 54c81a1 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:49:46 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8a527dda13c9bec955b1f7e8db5822d1d9b32a01 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:48:05 2012 +0800 Ensure sequences are reset correctly in the presence of swapped models. commit e2b6e22f298eb986d74d28b8d9906f37f5ff8eb8 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 17:53:05 2012 +0800 Modifications to the handling and docs for auth forms. commit 98aba856b534620aea9091f824b442b47d2fdb3c Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 15:28:57 2012 +0800 Improved error handling and docs for get_user_model() commit 0229209c844f06dfeb33b0b8eeec000c127695b6 Merge: 6494bf9 8599f64 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 14:50:11 2012 +0800 Merged recent Django trunk changes. commit 6494bf91f2ddaaabec3ec017f2e3131937c35517 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 21:38:44 2012 +0800 Improved validation of swappable model settings. commit 5a04cde342cc860384eb844cfda5af55204564ad Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 07:15:14 2012 +0800 Removed some unused imports. commit ffd535e4136dc54f084b6ac467e81444696e1c8a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:31:28 2012 +0800 Corrected attribute access on for get_by_natural_key commit 913e1ac84c3d9c7c58a9b3bdbbb15ebccd8a8c0a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:12:34 2012 +0800 Added test for proxy model safeguards on swappable models. commit 280bf19e94d0d534d0e51bae485c1842558f4ff4 Merge: dbb3900 935a863 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:16:49 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit dbb3900775a99df8b6cb1d7063cf364eab55621a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:09:27 2012 +0800 Fixes for Python 3 compatibility. commit dfd72131d8664615e245aa0f95b82604ba6b3821 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:54:30 2012 +0800 Added protection against proxying swapped models. commit abcb027190e53613e7f1734e77ee185b2587de31 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:11:10 2012 +0800 Cleanup and documentation of AbstractUser base class. commit a9491a87763e307f0eb0dc246f54ac865a6ffb34 Merge: fd8bb4e 08bcb4a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:46:49 2012 +0800 Merge commit '08bcb4aec1ed154cefc631b8510ee13e9af0c19d' into t3011 commit fd8bb4e3e498a92d7a8b340f0684d5f088aa4c92 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:20:14 2012 +0800 Documentation improvements coming from community review. commit b550a6d06d016ab6a0198c4cb2dffe9cceabe8a5 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:52:47 2012 +0800 Refactored skipIfCustomUser into the contrib.auth tests. commit 52a02f11107c3f0d711742b8ca65b75175b79d6a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:46:10 2012 +0800 Refactored common 'get' pattern into manager method. commit b441a6bbc7d6065175715cb09316b9f13268171b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:41:33 2012 +0800 Added note about backwards incompatible change to admin login messages. commit 08bcb4aec1ed154cefc631b8510ee13e9af0c19d Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:33 2012 +0300 Splitted User to AbstractUser and User commit d9f5e5addbad5e1a01f67e7358e4f5091c3cad81 Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:02 2012 +0300 Reworked REQUIRED_FIELDS + create_user() interaction commit 579f152e4a6e06671e1ac1e59e2b43cf4d764bf4 Merge: 9184972 93e6733 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:37 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 918497218c58227f5032873ff97261627b2ceab2 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:19 2012 +0800 Deprecate AUTH_PROFILE_MODULE and get_profile(). commit 334cdfc1bb6a6794791497cdefda843bca2ea57a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:00:12 2012 +0800 Added release notes for new swappable User feature. commit 5d7bb22e8d913b51aba1c3360e7af8b01b6c0ab6 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 19:59:49 2012 +0800 Ensure swapped models can't be queried. commit 57ac6e3d32605a67581e875b37ec5b2284711a32 Merge: f2ec915 abfba3b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 14:31:54 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit f2ec915b20f81c8afeaa3df25f80689712f720f8 Merge: 1952656 5e99a3d Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:29:51 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 19526563b54fa300785c49cfb625c0c6158ced67 Merge: 2c5e833 c4aa26a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:22:26 2012 +0800 Merge recent changes from master. commit 2c5e833a30bef4305d55eacc0703533152f5c427 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 07:53:46 2012 +0800 Corrected admin_views tests following removal of the email fallback on admin logins. commit 20d1892491839d6ef21f37db4ca136935c2076bf Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 01:00:37 2012 +0800 Added conditional skips for all tests dependent on the default User model commit 40ea8b888284775481fc1eaadeff267dbd7e3dfa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:47:02 2012 +0800 Added documentation for REQUIRED_FIELDS in custom auth. commit e6aaf659708cf6491f5485d3edfa616cb9214cc0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:20:02 2012 +0800 Added first draft of custom User docs. Thanks to Greg Turner for the initial text. commit 75118bd242eec87649da2859e8c50a199a8a1dca Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 11:17:26 2012 +0800 Admin app should not allow username discovery The admin app login form should not allow users to discover the username associated with an email address. commit d088b3af58dad7449fc58493193a327725c57c22 Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 10:32:13 2012 +0800 Admin app login form should use swapped user model commit 7e82e83d67ee0871a72e1a3a723afdd214fcefc3 Merge: e29c010 39aa890 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Fri Sep 7 23:45:03 2012 +0800 Merged master changes. commit e29c010beb96ca07697c4e3e0c0d5d3ffdc4c0a3 Merge: 8e3fd70 30bdf22 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:12:57 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8e3fd703d02c31a4c3ac9f51f5011d03c0bd47f6 Merge: 507bb50 26e0ba0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:09:09 2012 +0800 Merged recent changes from trunk. commit 507bb50a9291bfcdcfa1198f9fea21d4e3b1e762 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:41:37 2012 +0800 Modified auth app so that login with alternate auth app is possible. commit dabe3628362ab7a4a6c9686dd874803baa997eaa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:10:51 2012 +0800 Modified auth management commands to handle custom user definitions. commit 7cc0baf89d490c92ef3f1dc909b8090191a1294b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 14:17:28 2012 +0800 Added model Meta option for swappable models, and made auth.User a swappable model
2012-09-26 18:48:09 +08:00
self[key]
except KeyError:
return False
return True
def keys(self):
"""
Flattened keys of subcontexts.
"""
keys = set()
for subcontext in self:
for dict in subcontext:
keys |= set(dict.keys())
return keys
def instrumented_test_render(self, context):
"""
An instrumented Template render method, providing a signal
that can be intercepted by the test system Client
"""
template_rendered.send(sender=self, template=self, context=context)
return self.nodelist.render(context)
def setup_test_environment():
"""Perform any global pre-test setup. This involves:
- Installing the instrumented test renderer
- Set the email backend to the locmem email backend.
- Setting the active locale to match the LANGUAGE_CODE setting.
"""
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
Template._original_render = Template._render
Template._render = instrumented_test_render
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
# Storing previous values in the settings module itself is problematic.
# Store them in arbitrary (but related) modules instead. See #20636.
mail._original_email_backend = settings.EMAIL_BACKEND
settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
request._original_allowed_hosts = settings.ALLOWED_HOSTS
settings.ALLOWED_HOSTS = ['*']
mail.outbox = []
deactivate()
def teardown_test_environment():
"""Perform any global post-test teardown. This involves:
- Restoring the original test renderer
- Restoring the email sending functions
"""
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
Template._render = Template._original_render
del Template._original_render
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
settings.EMAIL_BACKEND = mail._original_email_backend
del mail._original_email_backend
Fixed #20636 -- Stopped stuffing values in the settings. In Django < 1.6, override_settings restores the settings module that was active when the override_settings call was executed, not when it was run. This can make a difference when override_settings is applied to a class, since it's executed when the module is imported, not when the test case is run. In addition, if the settings module for tests is stored alongside the tests themselves, importing the settings module can trigger an import of the tests. Since the settings module isn't fully imported yet, class-level override_settings statements may store a reference to an incorrect settings module. Eventually this will result in a crash during test teardown because the settings module restored by override_settings won't the one that was active during test setup. While Django should prevent this situation in the future by failing loudly in such dubious import sequences, that change won't be backported to 1.5 and 1.4. However, these versions received the "allowed hosts" patch and they're prone to "AttributeError: 'Settings' object has no attribute '_original_allowed_hosts'". To mitigate this regression, this commits stuffs _original_allowed_hosts on a random module instead of the settings module. This problem shouldn't occur in Django 1.6, see #20290, but this patch will be forward-ported for extra safety. Also tweaked backup variable names for consistency. Forward port of 0261922 from stable/1.5.x. Conflicts: django/test/utils.py
2013-06-25 01:48:23 +08:00
settings.ALLOWED_HOSTS = request._original_allowed_hosts
del request._original_allowed_hosts
del mail.outbox
def get_runner(settings, test_runner_class=None):
if not test_runner_class:
test_runner_class = settings.TEST_RUNNER
test_path = test_runner_class.split('.')
# Allow for Python 2.5 relative paths
if len(test_path) > 1:
test_module_name = '.'.join(test_path[:-1])
else:
test_module_name = '.'
test_module = __import__(test_module_name, {}, {}, force_str(test_path[-1]))
test_runner = getattr(test_module, test_path[-1])
return test_runner
class override_template_loaders(object):
"""
Acts as a function decorator, context manager or start/end manager and
override the template loaders. It could be used in the following ways:
@override_template_loaders(SomeLoader())
def test_function(self):
...
with override_template_loaders(SomeLoader(), OtherLoader()) as loaders:
...
loaders = override_template_loaders.override(SomeLoader())
...
override_template_loaders.restore()
"""
def __init__(self, *loaders):
self.loaders = loaders
self.old_loaders = []
def __enter__(self):
self.old_loaders = loader.template_source_loaders
loader.template_source_loaders = self.loaders
return self.loaders
def __exit__(self, type, value, traceback):
loader.template_source_loaders = self.old_loaders
def __call__(self, test_func):
@wraps(test_func)
def inner(*args, **kwargs):
with self:
return test_func(*args, **kwargs)
return inner
@classmethod
def override(cls, *loaders):
if hasattr(loader, RESTORE_LOADERS_ATTR):
raise Exception("loader.%s already exists" % RESTORE_LOADERS_ATTR)
setattr(loader, RESTORE_LOADERS_ATTR, loader.template_source_loaders)
loader.template_source_loaders = loaders
return loaders
@classmethod
def restore(cls):
loader.template_source_loaders = getattr(loader, RESTORE_LOADERS_ATTR)
delattr(loader, RESTORE_LOADERS_ATTR)
class TestTemplateLoader(loader.BaseLoader):
"A custom template loader that loads templates from a dictionary."
is_usable = True
def __init__(self, templates_dict):
self.templates_dict = templates_dict
def load_template_source(self, template_name, template_dirs=None,
skip_template=None):
try:
return (self.templates_dict[template_name],
"test:%s" % template_name)
except KeyError:
raise TemplateDoesNotExist(template_name)
class override_with_test_loader(override_template_loaders):
"""
Acts as a function decorator, context manager or start/end manager and
override the template loaders with the test loader. It could be used in the
following ways:
@override_with_test_loader(templates_dict, use_cached_loader=True)
def test_function(self):
...
with override_with_test_loader(templates_dict) as test_loader:
...
test_loader = override_with_test_loader.override(templates_dict)
...
override_with_test_loader.restore()
"""
def __init__(self, templates_dict, use_cached_loader=False):
self.loader = self._get_loader(templates_dict, use_cached_loader)
super(override_with_test_loader, self).__init__(self.loader)
def __enter__(self):
return super(override_with_test_loader, self).__enter__()[0]
@classmethod
def override(cls, templates_dict, use_cached_loader=False):
loader = cls._get_loader(templates_dict, use_cached_loader)
return super(override_with_test_loader, cls).override(loader)[0]
@classmethod
def _get_loader(cls, templates_dict, use_cached_loader=False):
if use_cached_loader:
loader = cached.Loader(('TestTemplateLoader',))
loader._cached_loaders = TestTemplateLoader(templates_dict)
return TestTemplateLoader(templates_dict)
class override_settings(object):
"""
Acts as either a decorator, or a context manager. If it's a decorator it
takes a function and returns a wrapped function. If it's a contextmanager
it's used with the ``with`` statement. In either event entering/exiting
are called before and after, respectively, the function/block is executed.
"""
def __init__(self, **kwargs):
self.options = kwargs
def __enter__(self):
self.enable()
def __exit__(self, exc_type, exc_value, traceback):
self.disable()
def __call__(self, test_func):
from django.test import SimpleTestCase
if isinstance(test_func, type):
if not issubclass(test_func, SimpleTestCase):
raise Exception(
"Only subclasses of Django SimpleTestCase can be decorated "
"with override_settings")
self.save_options(test_func)
return test_func
else:
@wraps(test_func)
def inner(*args, **kwargs):
with self:
return test_func(*args, **kwargs)
return inner
def save_options(self, test_func):
if test_func._overridden_settings is None:
test_func._overridden_settings = self.options
else:
# Duplicate dict to prevent subclasses from altering their parent.
test_func._overridden_settings = dict(
test_func._overridden_settings, **self.options)
def enable(self):
# Keep this code at the beginning to leave the settings unchanged
# in case it raises an exception because INSTALLED_APPS is invalid.
if 'INSTALLED_APPS' in self.options:
try:
apps.set_installed_apps(self.options['INSTALLED_APPS'])
except Exception:
apps.unset_installed_apps()
raise
override = UserSettingsHolder(settings._wrapped)
for key, new_value in self.options.items():
setattr(override, key, new_value)
self.wrapped = settings._wrapped
settings._wrapped = override
for key, new_value in self.options.items():
setting_changed.send(sender=settings._wrapped.__class__,
setting=key, value=new_value, enter=True)
def disable(self):
if 'INSTALLED_APPS' in self.options:
apps.unset_installed_apps()
settings._wrapped = self.wrapped
del self.wrapped
for key in self.options:
new_value = getattr(settings, key, None)
setting_changed.send(sender=settings._wrapped.__class__,
setting=key, value=new_value, enter=False)
Fixed #3011 -- Added swappable auth.User models. Thanks to the many people that contributed to the development and review of this patch, including (but not limited to) Jacob Kaplan-Moss, Anssi Kääriäinen, Ramiro Morales, Preston Holmes, Josh Ourisman, Thomas Sutton, and Roger Barnes, as well as the many, many people who have contributed to the design discussion around this ticket over many years. Squashed commit of the following: commit d84749a0f034a0a6906d20df047086b1219040d0 Merge: 531e771 7c11b1a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 18:37:04 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 531e7715da545f930c49919a19e954d41c59b446 Merge: 29d1abb 1f84b04 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Wed Sep 26 07:09:23 2012 +0800 Merged recent trunk changes. commit 29d1abbe351fd5da855fe5ce09e24227d90ddc91 Merge: 8a527dd 54c81a1 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:49:46 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8a527dda13c9bec955b1f7e8db5822d1d9b32a01 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 24 07:48:05 2012 +0800 Ensure sequences are reset correctly in the presence of swapped models. commit e2b6e22f298eb986d74d28b8d9906f37f5ff8eb8 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 17:53:05 2012 +0800 Modifications to the handling and docs for auth forms. commit 98aba856b534620aea9091f824b442b47d2fdb3c Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 15:28:57 2012 +0800 Improved error handling and docs for get_user_model() commit 0229209c844f06dfeb33b0b8eeec000c127695b6 Merge: 6494bf9 8599f64 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 23 14:50:11 2012 +0800 Merged recent Django trunk changes. commit 6494bf91f2ddaaabec3ec017f2e3131937c35517 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 21:38:44 2012 +0800 Improved validation of swappable model settings. commit 5a04cde342cc860384eb844cfda5af55204564ad Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Sep 17 07:15:14 2012 +0800 Removed some unused imports. commit ffd535e4136dc54f084b6ac467e81444696e1c8a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:31:28 2012 +0800 Corrected attribute access on for get_by_natural_key commit 913e1ac84c3d9c7c58a9b3bdbbb15ebccd8a8c0a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 20:12:34 2012 +0800 Added test for proxy model safeguards on swappable models. commit 280bf19e94d0d534d0e51bae485c1842558f4ff4 Merge: dbb3900 935a863 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:16:49 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit dbb3900775a99df8b6cb1d7063cf364eab55621a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 18:09:27 2012 +0800 Fixes for Python 3 compatibility. commit dfd72131d8664615e245aa0f95b82604ba6b3821 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:54:30 2012 +0800 Added protection against proxying swapped models. commit abcb027190e53613e7f1734e77ee185b2587de31 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 15:11:10 2012 +0800 Cleanup and documentation of AbstractUser base class. commit a9491a87763e307f0eb0dc246f54ac865a6ffb34 Merge: fd8bb4e 08bcb4a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:46:49 2012 +0800 Merge commit '08bcb4aec1ed154cefc631b8510ee13e9af0c19d' into t3011 commit fd8bb4e3e498a92d7a8b340f0684d5f088aa4c92 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 14:20:14 2012 +0800 Documentation improvements coming from community review. commit b550a6d06d016ab6a0198c4cb2dffe9cceabe8a5 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:52:47 2012 +0800 Refactored skipIfCustomUser into the contrib.auth tests. commit 52a02f11107c3f0d711742b8ca65b75175b79d6a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:46:10 2012 +0800 Refactored common 'get' pattern into manager method. commit b441a6bbc7d6065175715cb09316b9f13268171b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 16 13:41:33 2012 +0800 Added note about backwards incompatible change to admin login messages. commit 08bcb4aec1ed154cefc631b8510ee13e9af0c19d Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:33 2012 +0300 Splitted User to AbstractUser and User commit d9f5e5addbad5e1a01f67e7358e4f5091c3cad81 Author: Anssi Kääriäinen <akaariai@gmail.com> Date: Sat Sep 15 18:30:02 2012 +0300 Reworked REQUIRED_FIELDS + create_user() interaction commit 579f152e4a6e06671e1ac1e59e2b43cf4d764bf4 Merge: 9184972 93e6733 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:37 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 918497218c58227f5032873ff97261627b2ceab2 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:18:19 2012 +0800 Deprecate AUTH_PROFILE_MODULE and get_profile(). commit 334cdfc1bb6a6794791497cdefda843bca2ea57a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 20:00:12 2012 +0800 Added release notes for new swappable User feature. commit 5d7bb22e8d913b51aba1c3360e7af8b01b6c0ab6 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 19:59:49 2012 +0800 Ensure swapped models can't be queried. commit 57ac6e3d32605a67581e875b37ec5b2284711a32 Merge: f2ec915 abfba3b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 15 14:31:54 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit f2ec915b20f81c8afeaa3df25f80689712f720f8 Merge: 1952656 5e99a3d Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:29:51 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 19526563b54fa300785c49cfb625c0c6158ced67 Merge: 2c5e833 c4aa26a Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 08:22:26 2012 +0800 Merge recent changes from master. commit 2c5e833a30bef4305d55eacc0703533152f5c427 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 07:53:46 2012 +0800 Corrected admin_views tests following removal of the email fallback on admin logins. commit 20d1892491839d6ef21f37db4ca136935c2076bf Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sun Sep 9 01:00:37 2012 +0800 Added conditional skips for all tests dependent on the default User model commit 40ea8b888284775481fc1eaadeff267dbd7e3dfa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:47:02 2012 +0800 Added documentation for REQUIRED_FIELDS in custom auth. commit e6aaf659708cf6491f5485d3edfa616cb9214cc0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Sat Sep 8 23:20:02 2012 +0800 Added first draft of custom User docs. Thanks to Greg Turner for the initial text. commit 75118bd242eec87649da2859e8c50a199a8a1dca Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 11:17:26 2012 +0800 Admin app should not allow username discovery The admin app login form should not allow users to discover the username associated with an email address. commit d088b3af58dad7449fc58493193a327725c57c22 Author: Thomas Sutton <me@thomas-sutton.id.au> Date: Mon Aug 20 10:32:13 2012 +0800 Admin app login form should use swapped user model commit 7e82e83d67ee0871a72e1a3a723afdd214fcefc3 Merge: e29c010 39aa890 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Fri Sep 7 23:45:03 2012 +0800 Merged master changes. commit e29c010beb96ca07697c4e3e0c0d5d3ffdc4c0a3 Merge: 8e3fd70 30bdf22 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:12:57 2012 +0800 Merge remote-tracking branch 'django/master' into t3011 commit 8e3fd703d02c31a4c3ac9f51f5011d03c0bd47f6 Merge: 507bb50 26e0ba0 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Aug 20 13:09:09 2012 +0800 Merged recent changes from trunk. commit 507bb50a9291bfcdcfa1198f9fea21d4e3b1e762 Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:41:37 2012 +0800 Modified auth app so that login with alternate auth app is possible. commit dabe3628362ab7a4a6c9686dd874803baa997eaa Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 20:10:51 2012 +0800 Modified auth management commands to handle custom user definitions. commit 7cc0baf89d490c92ef3f1dc909b8090191a1294b Author: Russell Keith-Magee <russell@keith-magee.com> Date: Mon Jun 4 14:17:28 2012 +0800 Added model Meta option for swappable models, and made auth.User a swappable model
2012-09-26 18:48:09 +08:00
class modify_settings(override_settings):
"""
Like override_settings, but makes it possible to append, prepend or remove
items instead of redefining the entire list.
"""
def __init__(self, *args, **kwargs):
if args:
# Hack used when instantiating from SimpleTestCase._pre_setup.
assert not kwargs
self.operations = args[0]
else:
assert not args
self.operations = list(kwargs.items())
def save_options(self, test_func):
if test_func._modified_settings is None:
test_func._modified_settings = self.operations
else:
# Duplicate list to prevent subclasses from altering their parent.
test_func._modified_settings = list(
test_func._modified_settings) + self.operations
def enable(self):
self.options = {}
for name, operations in self.operations:
try:
# When called from SimpleTestCase._pre_setup, values may be
# overridden several times; cumulate changes.
value = self.options[name]
except KeyError:
value = list(getattr(settings, name, []))
for action, items in operations.items():
# items my be a single value or an iterable.
if isinstance(items, six.string_types):
items = [items]
if action == 'append':
value = value + [item for item in items if item not in value]
elif action == 'prepend':
value = [item for item in items if item not in value] + value
elif action == 'remove':
value = [item for item in value if item not in items]
else:
raise ValueError("Unsupported action: %s" % action)
self.options[name] = value
super(modify_settings, self).enable()
def override_system_checks(new_checks):
""" Acts as a decorator. Overrides list of registered system checks.
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
you also need to exclude its system checks. """
from django.core.checks.registry import registry
def outer(test_func):
@wraps(test_func)
def inner(*args, **kwargs):
old_checks = registry.registered_checks
registry.registered_checks = new_checks
try:
return test_func(*args, **kwargs)
finally:
registry.registered_checks = old_checks
return inner
return outer
def compare_xml(want, got):
"""Tries to do a 'xml-comparison' of want and got. Plain string
comparison doesn't always work because, for example, attribute
ordering should not be important. Comment nodes are not considered in the
comparison.
Based on http://codespeak.net/svn/lxml/trunk/src/lxml/doctestcompare.py
"""
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
def norm_whitespace(v):
return _norm_whitespace_re.sub(' ', v)
def child_text(element):
return ''.join([c.data for c in element.childNodes
if c.nodeType == Node.TEXT_NODE])
def children(element):
return [c for c in element.childNodes
if c.nodeType == Node.ELEMENT_NODE]
def norm_child_text(element):
return norm_whitespace(child_text(element))
def attrs_dict(element):
return dict(element.attributes.items())
def check_element(want_element, got_element):
if want_element.tagName != got_element.tagName:
return False
if norm_child_text(want_element) != norm_child_text(got_element):
return False
if attrs_dict(want_element) != attrs_dict(got_element):
return False
want_children = children(want_element)
got_children = children(got_element)
if len(want_children) != len(got_children):
return False
for want, got in zip(want_children, got_children):
if not check_element(want, got):
return False
return True
def first_node(document):
for node in document.childNodes:
if node.nodeType != Node.COMMENT_NODE:
return node
want, got = strip_quotes(want, got)
want = want.replace('\\n', '\n')
got = got.replace('\\n', '\n')
# If the string is not a complete xml document, we may need to add a
# root element. This allow us to compare fragments, like "<foo/><bar/>"
if not want.startswith('<?xml'):
wrapper = '<root>%s</root>'
want = wrapper % want
got = wrapper % got
# Parse the want and got strings, and compare the parsings.
want_root = first_node(parseString(want))
got_root = first_node(parseString(got))
return check_element(want_root, got_root)
def strip_quotes(want, got):
"""
Strip quotes of doctests output values:
>>> strip_quotes("'foo'")
"foo"
>>> strip_quotes('"foo"')
"foo"
"""
def is_quoted_string(s):
s = s.strip()
return (len(s) >= 2
and s[0] == s[-1]
and s[0] in ('"', "'"))
def is_quoted_unicode(s):
s = s.strip()
return (len(s) >= 3
and s[0] == 'u'
and s[1] == s[-1]
and s[1] in ('"', "'"))
if is_quoted_string(want) and is_quoted_string(got):
want = want.strip()[1:-1]
got = got.strip()[1:-1]
elif is_quoted_unicode(want) and is_quoted_unicode(got):
want = want.strip()[2:-1]
got = got.strip()[2:-1]
return want, got
def str_prefix(s):
2012-08-11 19:34:35 +08:00
return s % {'_': '' if six.PY3 else 'u'}
class CaptureQueriesContext(object):
"""
Context manager that captures queries executed by the specified connection.
"""
def __init__(self, connection):
self.connection = connection
def __iter__(self):
return iter(self.captured_queries)
def __getitem__(self, index):
return self.captured_queries[index]
def __len__(self):
return len(self.captured_queries)
@property
def captured_queries(self):
return self.connection.queries[self.initial_queries:self.final_queries]
def __enter__(self):
self.use_debug_cursor = self.connection.use_debug_cursor
self.connection.use_debug_cursor = True
self.initial_queries = len(self.connection.queries_log)
self.final_queries = None
request_started.disconnect(reset_queries)
return self
def __exit__(self, exc_type, exc_value, traceback):
self.connection.use_debug_cursor = self.use_debug_cursor
request_started.connect(reset_queries)
if exc_type is not None:
return
self.final_queries = len(self.connection.queries_log)
class IgnoreDeprecationWarningsMixin(object):
2014-03-23 04:08:59 +08:00
warning_classes = [RemovedInDjango19Warning]
def setUp(self):
super(IgnoreDeprecationWarningsMixin, self).setUp()
self.catch_warnings = warnings.catch_warnings()
self.catch_warnings.__enter__()
for warning_class in self.warning_classes:
warnings.filterwarnings("ignore", category=warning_class)
def tearDown(self):
self.catch_warnings.__exit__(*sys.exc_info())
super(IgnoreDeprecationWarningsMixin, self).tearDown()
class IgnorePendingDeprecationWarningsMixin(IgnoreDeprecationWarningsMixin):
2014-03-23 04:08:59 +08:00
warning_classes = [RemovedInDjango20Warning]
class IgnoreAllDeprecationWarningsMixin(IgnoreDeprecationWarningsMixin):
2014-03-23 04:08:59 +08:00
warning_classes = [RemovedInDjango20Warning, RemovedInDjango19Warning]
@contextmanager
def patch_logger(logger_name, log_level):
"""
Context manager that takes a named logger and the logging level
and provides a simple mock-like list of messages received
"""
calls = []
def replacement(msg, *args, **kwargs):
calls.append(msg % args)
logger = logging.getLogger(logger_name)
orig = getattr(logger, log_level)
setattr(logger, log_level, replacement)
try:
yield calls
finally:
setattr(logger, log_level, orig)
# On OSes that don't provide tzset (Windows), we can't set the timezone
# in which the program runs. As a consequence, we must skip tests that
# don't enforce a specific timezone (with timezone.override or equivalent),
# or attempt to interpret naive datetimes in the default timezone.
requires_tz_support = skipUnless(TZ_SUPPORT,
"This test relies on the ability to run a program in an arbitrary "
"time zone, but your operating system isn't able to do that.")
@contextmanager
def extend_sys_path(*paths):
"""Context manager to temporarily add paths to sys.path."""
_orig_sys_path = sys.path[:]
sys.path.extend(paths)
try:
yield
finally:
sys.path = _orig_sys_path