2016-07-03 06:20:14 +08:00
|
|
|
import collections
|
2013-05-16 07:14:28 +08:00
|
|
|
import logging
|
2012-10-06 19:14:11 +08:00
|
|
|
import re
|
2013-05-18 22:40:03 +08:00
|
|
|
import sys
|
2013-10-01 15:27:31 +08:00
|
|
|
import time
|
2010-11-11 23:06:20 +08:00
|
|
|
import warnings
|
2015-01-28 20:35:27 +08:00
|
|
|
from contextlib import contextmanager
|
2013-05-04 17:53:12 +08:00
|
|
|
from functools import wraps
|
2017-01-07 19:11:46 +08:00
|
|
|
from io import StringIO
|
2017-04-27 20:16:19 +08:00
|
|
|
from itertools import chain
|
2016-12-01 18:38:01 +08:00
|
|
|
from types import SimpleNamespace
|
2015-11-20 11:27:37 +08:00
|
|
|
from unittest import TestCase, skipIf, skipUnless
|
2015-01-28 20:35:27 +08:00
|
|
|
from xml.dom.minidom import Node, parseString
|
2012-10-06 19:14:11 +08:00
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2015-11-17 13:33:18 +08:00
|
|
|
from django.apps.registry import Apps
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.conf import UserSettingsHolder, settings
|
2007-08-16 14:06:55 +08:00
|
|
|
from django.core import mail
|
2016-07-03 06:20:14 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured
|
2013-03-02 04:29:39 +08:00
|
|
|
from django.core.signals import request_started
|
2016-07-03 06:20:14 +08:00
|
|
|
from django.db import DEFAULT_DB_ALIAS, connections, reset_queries
|
2015-11-17 13:33:18 +08:00
|
|
|
from django.db.models.options import Options
|
2014-11-16 03:41:30 +08:00
|
|
|
from django.template import Template
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.test.signals import setting_changed, template_rendered
|
2015-12-30 23:51:16 +08:00
|
|
|
from django.urls import get_script_prefix, set_script_prefix
|
2013-02-16 20:26:36 +08:00
|
|
|
from django.utils.translation import deactivate
|
2011-05-18 20:08:53 +08:00
|
|
|
|
2015-01-27 04:57:10 +08:00
|
|
|
try:
|
|
|
|
import jinja2
|
|
|
|
except ImportError:
|
|
|
|
jinja2 = None
|
|
|
|
|
2006-08-27 20:24:59 +08:00
|
|
|
|
2011-05-18 20:08:53 +08:00
|
|
|
__all__ = (
|
2015-08-22 21:40:34 +08:00
|
|
|
'Approximate', 'ContextList', 'isolate_lru_cache', 'get_runner',
|
2013-12-23 19:39:19 +08:00
|
|
|
'modify_settings', 'override_settings',
|
|
|
|
'requires_tz_support',
|
|
|
|
'setup_test_environment', 'teardown_test_environment',
|
2011-05-18 20:08:53 +08:00
|
|
|
)
|
2010-08-20 22:28:42 +08:00
|
|
|
|
2013-10-01 15:27:31 +08:00
|
|
|
TZ_SUPPORT = hasattr(time, 'tzset')
|
2011-04-17 12:52:17 +08:00
|
|
|
|
2010-10-19 00:08:25 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Approximate:
|
2010-08-20 22:28:42 +08:00
|
|
|
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
|
2010-08-20 22:28:42 +08:00
|
|
|
|
|
|
|
|
2009-03-18 18:46:55 +08:00
|
|
|
class ContextList(list):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
A wrapper that provides direct key access to context items contained
|
2009-03-18 18:46:55 +08:00
|
|
|
in a list of context objects.
|
|
|
|
"""
|
|
|
|
def __getitem__(self, key):
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(key, str):
|
2009-03-18 18:46:55 +08:00
|
|
|
for subcontext in self:
|
|
|
|
if key in subcontext:
|
|
|
|
return subcontext[key]
|
2010-01-22 23:31:14 +08:00
|
|
|
raise KeyError(key)
|
2009-03-18 18:46:55 +08:00
|
|
|
else:
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().__getitem__(key)
|
2009-03-18 18:46:55 +08:00
|
|
|
|
2017-01-07 08:23:42 +08:00
|
|
|
def get(self, key, default=None):
|
|
|
|
try:
|
|
|
|
return self.__getitem__(key)
|
|
|
|
except KeyError:
|
|
|
|
return default
|
|
|
|
|
2010-08-07 00:34:34 +08:00
|
|
|
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]
|
2010-08-07 00:34:34 +08:00
|
|
|
except KeyError:
|
|
|
|
return False
|
|
|
|
return True
|
2009-03-18 18:46:55 +08:00
|
|
|
|
2013-05-14 00:38:29 +08:00
|
|
|
def keys(self):
|
|
|
|
"""
|
|
|
|
Flattened keys of subcontexts.
|
|
|
|
"""
|
2017-04-27 20:16:19 +08:00
|
|
|
return set(chain.from_iterable(d for subcontext in self for d in subcontext))
|
2013-05-14 00:38:29 +08:00
|
|
|
|
2010-11-11 23:06:20 +08:00
|
|
|
|
2006-09-02 17:26:24 +08:00
|
|
|
def instrumented_test_render(self, context):
|
Merged Unicode branch into trunk (r4952:5608). This should be fully
backwards compatible for all practical purposes.
Fixed #2391, #2489, #2996, #3322, #3344, #3370, #3406, #3432, #3454, #3492, #3582, #3690, #3878, #3891, #3937, #4039, #4141, #4227, #4286, #4291, #4300, #4452, #4702
git-svn-id: http://code.djangoproject.com/svn/django/trunk@5609 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2007-07-04 20:11:04 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
An instrumented Template render method, providing a signal that can be
|
|
|
|
intercepted by the test Client.
|
2006-09-02 17:26:24 +08:00
|
|
|
"""
|
2011-05-18 20:08:53 +08:00
|
|
|
template_rendered.send(sender=self, template=self, context=context)
|
2006-09-02 17:26:24 +08:00
|
|
|
return self.nodelist.render(context)
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2007-05-08 19:19:34 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class _TestState:
|
2016-08-08 18:04:27 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def setup_test_environment(debug=None):
|
2016-08-05 02:29:59 +08:00
|
|
|
"""
|
|
|
|
Perform global pre-test setup, such as installing the instrumented template
|
|
|
|
renderer and setting the email backend to the locmem email backend.
|
2006-09-02 17:26:24 +08:00
|
|
|
"""
|
2016-08-13 22:56:57 +08:00
|
|
|
if hasattr(_TestState, 'saved_data'):
|
2016-08-08 17:38:10 +08:00
|
|
|
# Executing this function twice would overwrite the saved values.
|
|
|
|
raise RuntimeError(
|
|
|
|
"setup_test_environment() was already called and can't be called "
|
|
|
|
"again without first calling teardown_test_environment()."
|
|
|
|
)
|
|
|
|
|
2016-08-08 18:04:27 +08:00
|
|
|
if debug is None:
|
|
|
|
debug = settings.DEBUG
|
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data = SimpleNamespace()
|
|
|
|
_TestState.saved_data = saved_data
|
2016-08-08 18:04:27 +08:00
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data.allowed_hosts = settings.ALLOWED_HOSTS
|
|
|
|
# Add the default host of the test client.
|
2017-02-25 02:58:56 +08:00
|
|
|
settings.ALLOWED_HOSTS = list(settings.ALLOWED_HOSTS) + ['testserver']
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data.debug = settings.DEBUG
|
|
|
|
settings.DEBUG = debug
|
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
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data.email_backend = settings.EMAIL_BACKEND
|
2010-01-04 20:05:04 +08:00
|
|
|
settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
|
2007-05-08 19:19:34 +08:00
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data.template_render = Template._render
|
|
|
|
Template._render = instrumented_test_render
|
2013-02-10 01:17:01 +08:00
|
|
|
|
2007-05-08 19:19:34 +08:00
|
|
|
mail.outbox = []
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2007-10-22 01:26:32 +08:00
|
|
|
deactivate()
|
|
|
|
|
2010-11-11 23:06:20 +08:00
|
|
|
|
2006-09-02 17:26:24 +08:00
|
|
|
def teardown_test_environment():
|
2016-08-05 02:29:59 +08:00
|
|
|
"""
|
|
|
|
Perform any global post-test teardown, such as restoring the original
|
|
|
|
template renderer and restoring the email sending functions.
|
2006-09-02 17:26:24 +08:00
|
|
|
"""
|
2016-08-13 22:56:57 +08:00
|
|
|
saved_data = _TestState.saved_data
|
2007-08-16 14:06:55 +08:00
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
settings.ALLOWED_HOSTS = saved_data.allowed_hosts
|
|
|
|
settings.DEBUG = saved_data.debug
|
|
|
|
settings.EMAIL_BACKEND = saved_data.email_backend
|
|
|
|
Template._render = saved_data.template_render
|
2013-02-10 01:17:01 +08:00
|
|
|
|
2016-08-13 22:56:57 +08:00
|
|
|
del _TestState.saved_data
|
2009-11-03 20:53:26 +08:00
|
|
|
del mail.outbox
|
2009-02-28 12:46:38 +08:00
|
|
|
|
2010-11-11 23:06:20 +08:00
|
|
|
|
2016-07-03 06:20:14 +08:00
|
|
|
def setup_databases(verbosity, interactive, keepdb=False, debug_sql=False, parallel=0, **kwargs):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Create the test databases."""
|
2016-07-03 06:20:14 +08:00
|
|
|
test_databases, mirrored_aliases = get_unique_databases_and_mirrors()
|
|
|
|
|
|
|
|
old_names = []
|
|
|
|
|
2017-12-07 06:17:59 +08:00
|
|
|
for db_name, aliases in test_databases.values():
|
2016-07-03 06:20:14 +08:00
|
|
|
first_alias = None
|
|
|
|
for alias in aliases:
|
|
|
|
connection = connections[alias]
|
|
|
|
old_names.append((connection, db_name, first_alias is None))
|
|
|
|
|
|
|
|
# Actually create the database for the first connection
|
|
|
|
if first_alias is None:
|
|
|
|
first_alias = alias
|
|
|
|
connection.creation.create_test_db(
|
|
|
|
verbosity=verbosity,
|
|
|
|
autoclobber=not interactive,
|
|
|
|
keepdb=keepdb,
|
|
|
|
serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True),
|
|
|
|
)
|
|
|
|
if parallel > 1:
|
|
|
|
for index in range(parallel):
|
|
|
|
connection.creation.clone_test_db(
|
2017-09-11 23:32:40 +08:00
|
|
|
suffix=str(index + 1),
|
2016-07-03 06:20:14 +08:00
|
|
|
verbosity=verbosity,
|
|
|
|
keepdb=keepdb,
|
|
|
|
)
|
|
|
|
# Configure all other connections as mirrors of the first one
|
|
|
|
else:
|
|
|
|
connections[alias].creation.set_as_test_mirror(connections[first_alias].settings_dict)
|
|
|
|
|
|
|
|
# Configure the test mirrors.
|
|
|
|
for alias, mirror_alias in mirrored_aliases.items():
|
|
|
|
connections[alias].creation.set_as_test_mirror(
|
|
|
|
connections[mirror_alias].settings_dict)
|
|
|
|
|
|
|
|
if debug_sql:
|
|
|
|
for alias in connections:
|
|
|
|
connections[alias].force_debug_cursor = True
|
|
|
|
|
|
|
|
return old_names
|
|
|
|
|
|
|
|
|
|
|
|
def dependency_ordered(test_databases, dependencies):
|
|
|
|
"""
|
|
|
|
Reorder test_databases into an order that honors the dependencies
|
|
|
|
described in TEST[DEPENDENCIES].
|
|
|
|
"""
|
|
|
|
ordered_test_databases = []
|
|
|
|
resolved_databases = set()
|
|
|
|
|
|
|
|
# Maps db signature to dependencies of all its aliases
|
|
|
|
dependencies_map = {}
|
|
|
|
|
|
|
|
# Check that no database depends on its own alias
|
|
|
|
for sig, (_, aliases) in test_databases:
|
|
|
|
all_deps = set()
|
|
|
|
for alias in aliases:
|
|
|
|
all_deps.update(dependencies.get(alias, []))
|
|
|
|
if not all_deps.isdisjoint(aliases):
|
|
|
|
raise ImproperlyConfigured(
|
|
|
|
"Circular dependency: databases %r depend on each other, "
|
|
|
|
"but are aliases." % aliases
|
|
|
|
)
|
|
|
|
dependencies_map[sig] = all_deps
|
|
|
|
|
|
|
|
while test_databases:
|
|
|
|
changed = False
|
|
|
|
deferred = []
|
|
|
|
|
|
|
|
# Try to find a DB that has all its dependencies met
|
|
|
|
for signature, (db_name, aliases) in test_databases:
|
|
|
|
if dependencies_map[signature].issubset(resolved_databases):
|
|
|
|
resolved_databases.update(aliases)
|
|
|
|
ordered_test_databases.append((signature, (db_name, aliases)))
|
|
|
|
changed = True
|
|
|
|
else:
|
|
|
|
deferred.append((signature, (db_name, aliases)))
|
|
|
|
|
|
|
|
if not changed:
|
|
|
|
raise ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]")
|
|
|
|
test_databases = deferred
|
|
|
|
return ordered_test_databases
|
|
|
|
|
|
|
|
|
|
|
|
def get_unique_databases_and_mirrors():
|
|
|
|
"""
|
|
|
|
Figure out which databases actually need to be created.
|
|
|
|
|
|
|
|
Deduplicate entries in DATABASES that correspond the same database or are
|
|
|
|
configured as test mirrors.
|
|
|
|
|
|
|
|
Return two values:
|
|
|
|
- test_databases: ordered mapping of signatures to (name, list of aliases)
|
|
|
|
where all aliases share the same underlying database.
|
|
|
|
- mirrored_aliases: mapping of mirror aliases to original aliases.
|
|
|
|
"""
|
|
|
|
mirrored_aliases = {}
|
|
|
|
test_databases = {}
|
|
|
|
dependencies = {}
|
|
|
|
default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature()
|
|
|
|
|
|
|
|
for alias in connections:
|
|
|
|
connection = connections[alias]
|
|
|
|
test_settings = connection.settings_dict['TEST']
|
|
|
|
|
|
|
|
if test_settings['MIRROR']:
|
|
|
|
# If the database is marked as a test mirror, save the alias.
|
|
|
|
mirrored_aliases[alias] = test_settings['MIRROR']
|
|
|
|
else:
|
|
|
|
# Store a tuple with DB parameters that uniquely identify it.
|
|
|
|
# If we have two aliases with the same values for that tuple,
|
|
|
|
# we only need to create the test database once.
|
|
|
|
item = test_databases.setdefault(
|
|
|
|
connection.creation.test_db_signature(),
|
|
|
|
(connection.settings_dict['NAME'], set())
|
|
|
|
)
|
|
|
|
item[1].add(alias)
|
|
|
|
|
|
|
|
if 'DEPENDENCIES' in test_settings:
|
|
|
|
dependencies[alias] = test_settings['DEPENDENCIES']
|
|
|
|
else:
|
|
|
|
if alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig:
|
|
|
|
dependencies[alias] = test_settings.get('DEPENDENCIES', [DEFAULT_DB_ALIAS])
|
|
|
|
|
|
|
|
test_databases = dependency_ordered(test_databases.items(), dependencies)
|
|
|
|
test_databases = collections.OrderedDict(test_databases)
|
|
|
|
return test_databases, mirrored_aliases
|
|
|
|
|
|
|
|
|
|
|
|
def teardown_databases(old_config, verbosity, parallel=0, keepdb=False):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Destroy all the non-mirror databases."""
|
2016-07-03 06:20:14 +08:00
|
|
|
for connection, old_name, destroy in old_config:
|
|
|
|
if destroy:
|
|
|
|
if parallel > 1:
|
|
|
|
for index in range(parallel):
|
|
|
|
connection.creation.destroy_test_db(
|
2017-09-11 23:32:40 +08:00
|
|
|
suffix=str(index + 1),
|
2016-07-03 06:20:14 +08:00
|
|
|
verbosity=verbosity,
|
|
|
|
keepdb=keepdb,
|
|
|
|
)
|
|
|
|
connection.creation.destroy_test_db(old_name, verbosity, keepdb)
|
|
|
|
|
|
|
|
|
2011-06-10 16:26:05 +08:00
|
|
|
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('.')
|
2017-01-22 09:02:00 +08:00
|
|
|
# Allow for relative paths
|
2009-02-28 12:46:38 +08:00
|
|
|
if len(test_path) > 1:
|
|
|
|
test_module_name = '.'.join(test_path[:-1])
|
|
|
|
else:
|
|
|
|
test_module_name = '.'
|
2017-01-12 06:17:25 +08:00
|
|
|
test_module = __import__(test_module_name, {}, {}, test_path[-1])
|
2009-02-28 12:46:38 +08:00
|
|
|
test_runner = getattr(test_module, test_path[-1])
|
|
|
|
return test_runner
|
2011-04-17 12:52:17 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class TestContextDecorator:
|
2011-05-18 20:08:53 +08:00
|
|
|
"""
|
2015-11-20 11:27:37 +08:00
|
|
|
A base class that can either be used as a context manager during tests
|
|
|
|
or as a test function or unittest.TestCase subclass decorator to perform
|
|
|
|
temporary alterations.
|
|
|
|
|
|
|
|
`attr_name`: attribute assigned the return value of enable() if used as
|
|
|
|
a class decorator.
|
|
|
|
|
|
|
|
`kwarg_name`: keyword argument passing the return value of enable() if
|
|
|
|
used as a function decorator.
|
2011-05-18 20:08:53 +08:00
|
|
|
"""
|
2015-11-20 11:27:37 +08:00
|
|
|
def __init__(self, attr_name=None, kwarg_name=None):
|
|
|
|
self.attr_name = attr_name
|
|
|
|
self.kwarg_name = kwarg_name
|
|
|
|
|
|
|
|
def enable(self):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def disable(self):
|
|
|
|
raise NotImplementedError
|
2011-05-18 20:08:53 +08:00
|
|
|
|
|
|
|
def __enter__(self):
|
2015-11-20 11:27:37 +08:00
|
|
|
return self.enable()
|
2011-05-18 20:08:53 +08:00
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
self.disable()
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def decorate_class(self, cls):
|
|
|
|
if issubclass(cls, TestCase):
|
|
|
|
decorated_setUp = cls.setUp
|
|
|
|
decorated_tearDown = cls.tearDown
|
|
|
|
|
|
|
|
def setUp(inner_self):
|
|
|
|
context = self.enable()
|
|
|
|
if self.attr_name:
|
|
|
|
setattr(inner_self, self.attr_name, context)
|
|
|
|
decorated_setUp(inner_self)
|
|
|
|
|
|
|
|
def tearDown(inner_self):
|
|
|
|
decorated_tearDown(inner_self)
|
|
|
|
self.disable()
|
|
|
|
|
|
|
|
cls.setUp = setUp
|
|
|
|
cls.tearDown = tearDown
|
|
|
|
return cls
|
|
|
|
raise TypeError('Can only decorate subclasses of unittest.TestCase')
|
|
|
|
|
|
|
|
def decorate_callable(self, func):
|
2017-01-22 02:20:17 +08:00
|
|
|
@wraps(func)
|
2015-11-20 11:27:37 +08:00
|
|
|
def inner(*args, **kwargs):
|
|
|
|
with self as context:
|
|
|
|
if self.kwarg_name:
|
|
|
|
kwargs[self.kwarg_name] = context
|
|
|
|
return func(*args, **kwargs)
|
2011-05-18 20:08:53 +08:00
|
|
|
return inner
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def __call__(self, decorated):
|
|
|
|
if isinstance(decorated, type):
|
|
|
|
return self.decorate_class(decorated)
|
|
|
|
elif callable(decorated):
|
|
|
|
return self.decorate_callable(decorated)
|
|
|
|
raise TypeError('Cannot decorate object of type %s' % type(decorated))
|
|
|
|
|
|
|
|
|
|
|
|
class override_settings(TestContextDecorator):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Act as either a decorator or a context manager. If it's a decorator, take a
|
|
|
|
function and return a wrapped function. If it's a contextmanager, use it
|
|
|
|
with the ``with`` statement. In either event, entering/exiting are called
|
|
|
|
before and after, respectively, the function/block is executed.
|
2015-11-20 11:27:37 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, **kwargs):
|
|
|
|
self.options = kwargs
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2013-12-23 19:39:19 +08:00
|
|
|
|
2011-05-18 20:08:53 +08:00
|
|
|
def enable(self):
|
2013-12-24 07:07:54 +08:00
|
|
|
# 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:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.set_installed_apps(self.options['INSTALLED_APPS'])
|
2013-12-24 07:07:54 +08:00
|
|
|
except Exception:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.unset_installed_apps()
|
2013-12-24 07:07:54 +08:00
|
|
|
raise
|
2012-03-14 07:02:31 +08:00
|
|
|
override = UserSettingsHolder(settings._wrapped)
|
2011-05-18 20:08:53 +08:00
|
|
|
for key, new_value in self.options.items():
|
|
|
|
setattr(override, key, new_value)
|
2013-04-19 17:44:47 +08:00
|
|
|
self.wrapped = settings._wrapped
|
2011-05-18 20:08:53 +08:00
|
|
|
settings._wrapped = override
|
2012-03-14 07:02:31 +08:00
|
|
|
for key, new_value in self.options.items():
|
|
|
|
setting_changed.send(sender=settings._wrapped.__class__,
|
2013-05-18 19:43:51 +08:00
|
|
|
setting=key, value=new_value, enter=True)
|
2011-05-18 20:08:53 +08:00
|
|
|
|
|
|
|
def disable(self):
|
2013-12-23 19:39:19 +08:00
|
|
|
if 'INSTALLED_APPS' in self.options:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.unset_installed_apps()
|
2013-12-24 07:07:54 +08:00
|
|
|
settings._wrapped = self.wrapped
|
|
|
|
del self.wrapped
|
2012-03-14 07:02:31 +08:00
|
|
|
for key in self.options:
|
|
|
|
new_value = getattr(settings, key, None)
|
|
|
|
setting_changed.send(sender=settings._wrapped.__class__,
|
2013-05-18 19:43:51 +08:00
|
|
|
setting=key, value=new_value, enter=False)
|
2012-03-14 07:02:31 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
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.
|
2017-12-11 20:08:45 +08:00
|
|
|
test_func._overridden_settings = {
|
|
|
|
**test_func._overridden_settings,
|
|
|
|
**self.options,
|
|
|
|
}
|
2015-11-20 11:27:37 +08:00
|
|
|
|
|
|
|
def decorate_class(self, cls):
|
|
|
|
from django.test import SimpleTestCase
|
|
|
|
if not issubclass(cls, SimpleTestCase):
|
|
|
|
raise ValueError(
|
|
|
|
"Only subclasses of Django SimpleTestCase can be decorated "
|
|
|
|
"with override_settings")
|
|
|
|
self.save_options(cls)
|
|
|
|
return cls
|
|
|
|
|
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
|
|
|
|
2013-12-23 19:39:19 +08:00
|
|
|
class modify_settings(override_settings):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Like override_settings, but makes it possible to append, prepend, or remove
|
2013-12-23 19:39:19 +08:00
|
|
|
items instead of redefining the entire list.
|
|
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
if args:
|
2014-12-07 03:39:53 +08:00
|
|
|
# Hack used when instantiating from SimpleTestCase.setUpClass.
|
2013-12-23 19:39:19 +08:00
|
|
|
assert not kwargs
|
|
|
|
self.operations = args[0]
|
|
|
|
else:
|
|
|
|
assert not args
|
|
|
|
self.operations = list(kwargs.items())
|
2015-11-20 11:27:37 +08:00
|
|
|
super(override_settings, self).__init__()
|
2013-12-23 19:39:19 +08:00
|
|
|
|
|
|
|
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:
|
2014-12-07 03:39:53 +08:00
|
|
|
# When called from SimpleTestCase.setUpClass, values may be
|
2013-12-23 19:39:19 +08:00
|
|
|
# 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.
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(items, str):
|
2013-12-23 19:39:19 +08:00
|
|
|
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
|
2017-01-21 21:13:44 +08:00
|
|
|
super().enable()
|
2013-12-23 19:39:19 +08:00
|
|
|
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
class override_system_checks(TestContextDecorator):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Act as a decorator. Override list of registered system checks.
|
2014-01-20 10:45:21 +08:00
|
|
|
Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app,
|
2015-11-20 11:27:37 +08:00
|
|
|
you also need to exclude its system checks.
|
|
|
|
"""
|
|
|
|
def __init__(self, new_checks, deployment_checks=None):
|
|
|
|
from django.core.checks.registry import registry
|
|
|
|
self.registry = registry
|
|
|
|
self.new_checks = new_checks
|
|
|
|
self.deployment_checks = deployment_checks
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def enable(self):
|
|
|
|
self.old_checks = self.registry.registered_checks
|
2017-08-24 17:45:04 +08:00
|
|
|
self.registry.registered_checks = set()
|
2017-08-22 03:34:20 +08:00
|
|
|
for check in self.new_checks:
|
|
|
|
self.registry.register(check, *getattr(check, 'tags', ()))
|
2015-11-20 11:27:37 +08:00
|
|
|
self.old_deployment_checks = self.registry.deployment_checks
|
|
|
|
if self.deployment_checks is not None:
|
2017-08-24 17:45:04 +08:00
|
|
|
self.registry.deployment_checks = set()
|
2017-08-22 03:34:20 +08:00
|
|
|
for check in self.deployment_checks:
|
|
|
|
self.registry.register(check, *getattr(check, 'tags', ()), deploy=True)
|
2014-01-20 10:45:21 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def disable(self):
|
|
|
|
self.registry.registered_checks = self.old_checks
|
|
|
|
self.registry.deployment_checks = self.old_deployment_checks
|
2014-01-20 10:45:21 +08:00
|
|
|
|
|
|
|
|
2012-10-06 19:14:11 +08:00
|
|
|
def compare_xml(want, got):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
Try 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. Ignore comment nodes and leading and trailing whitespace.
|
2012-10-06 19:14:11 +08:00
|
|
|
|
2016-06-16 09:20:23 +08:00
|
|
|
Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py
|
2012-10-06 19:14:11 +08:00
|
|
|
"""
|
|
|
|
_norm_whitespace_re = re.compile(r'[ \t\n][ \t\n]+')
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2012-10-06 19:14:11 +08:00
|
|
|
def norm_whitespace(v):
|
|
|
|
return _norm_whitespace_re.sub(' ', v)
|
|
|
|
|
|
|
|
def child_text(element):
|
2014-12-07 05:00:09 +08:00
|
|
|
return ''.join(c.data for c in element.childNodes
|
|
|
|
if c.nodeType == Node.TEXT_NODE)
|
2012-10-06 19:14:11 +08:00
|
|
|
|
|
|
|
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
|
2017-12-27 02:44:12 +08:00
|
|
|
return all(check_element(want, got) for want, got in zip(want_children, got_children))
|
2012-10-06 19:14:11 +08:00
|
|
|
|
2012-10-16 04:18:47 +08:00
|
|
|
def first_node(document):
|
|
|
|
for node in document.childNodes:
|
|
|
|
if node.nodeType != Node.COMMENT_NODE:
|
|
|
|
return node
|
|
|
|
|
2015-11-07 21:31:25 +08:00
|
|
|
want = want.strip().replace('\\n', '\n')
|
|
|
|
got = got.strip().replace('\\n', '\n')
|
2012-10-06 19:14:11 +08:00
|
|
|
|
|
|
|
# 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.
|
2012-10-16 04:18:47 +08:00
|
|
|
want_root = first_node(parseString(want))
|
|
|
|
got_root = first_node(parseString(got))
|
2012-10-06 19:14:11 +08:00
|
|
|
|
|
|
|
return check_element(want_root, got_root)
|
|
|
|
|
|
|
|
|
2012-06-08 00:08:47 +08:00
|
|
|
def str_prefix(s):
|
2016-12-01 18:38:01 +08:00
|
|
|
return s % {'_': ''}
|
2013-03-02 04:29:39 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CaptureQueriesContext:
|
2013-03-02 04:29:39 +08:00
|
|
|
"""
|
|
|
|
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):
|
2014-07-26 19:06:49 +08:00
|
|
|
self.force_debug_cursor = self.connection.force_debug_cursor
|
|
|
|
self.connection.force_debug_cursor = True
|
2017-05-15 03:46:23 +08:00
|
|
|
# Run any initialization queries if needed so that they won't be
|
|
|
|
# included as part of the count.
|
|
|
|
self.connection.ensure_connection()
|
2014-06-07 20:09:27 +08:00
|
|
|
self.initial_queries = len(self.connection.queries_log)
|
2013-03-02 04:29:39 +08:00
|
|
|
self.final_queries = None
|
|
|
|
request_started.disconnect(reset_queries)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
2014-07-26 19:06:49 +08:00
|
|
|
self.connection.force_debug_cursor = self.force_debug_cursor
|
2013-03-02 04:29:39 +08:00
|
|
|
request_started.connect(reset_queries)
|
|
|
|
if exc_type is not None:
|
|
|
|
return
|
2014-06-07 20:09:27 +08:00
|
|
|
self.final_queries = len(self.connection.queries_log)
|
2013-05-18 22:40:03 +08:00
|
|
|
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
class ignore_warnings(TestContextDecorator):
|
2014-12-22 04:13:06 +08:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
self.ignore_kwargs = kwargs
|
|
|
|
if 'message' in self.ignore_kwargs or 'module' in self.ignore_kwargs:
|
|
|
|
self.filter_func = warnings.filterwarnings
|
|
|
|
else:
|
|
|
|
self.filter_func = warnings.simplefilter
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2014-12-22 04:13:06 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def enable(self):
|
|
|
|
self.catch_warnings = warnings.catch_warnings()
|
|
|
|
self.catch_warnings.__enter__()
|
|
|
|
self.filter_func('ignore', **self.ignore_kwargs)
|
2014-12-22 04:13:06 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def disable(self):
|
|
|
|
self.catch_warnings.__exit__(*sys.exc_info())
|
2013-05-16 07:14:28 +08:00
|
|
|
|
|
|
|
|
|
|
|
@contextmanager
|
2016-03-14 18:38:38 +08:00
|
|
|
def patch_logger(logger_name, log_level, log_kwargs=False):
|
2013-05-16 07:14:28 +08:00
|
|
|
"""
|
|
|
|
Context manager that takes a named logger and the logging level
|
|
|
|
and provides a simple mock-like list of messages received
|
|
|
|
"""
|
|
|
|
calls = []
|
2013-10-22 18:21:07 +08:00
|
|
|
|
2013-11-09 19:11:58 +08:00
|
|
|
def replacement(msg, *args, **kwargs):
|
2016-03-14 18:38:38 +08:00
|
|
|
call = msg % args
|
|
|
|
calls.append((call, kwargs) if log_kwargs else call)
|
2013-05-16 07:14:28 +08:00
|
|
|
logger = logging.getLogger(logger_name)
|
|
|
|
orig = getattr(logger, log_level)
|
|
|
|
setattr(logger, log_level, replacement)
|
|
|
|
try:
|
|
|
|
yield calls
|
|
|
|
finally:
|
|
|
|
setattr(logger, log_level, orig)
|
2013-10-01 15:27:31 +08:00
|
|
|
|
|
|
|
|
|
|
|
# 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.
|
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
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."
|
|
|
|
)
|
2014-01-26 13:50:40 +08:00
|
|
|
|
|
|
|
|
|
|
|
@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
|
2014-11-29 06:47:53 +08:00
|
|
|
|
|
|
|
|
2015-08-22 21:40:34 +08:00
|
|
|
@contextmanager
|
|
|
|
def isolate_lru_cache(lru_cache_object):
|
|
|
|
"""Clear the cache of an LRU cache object on entering and exiting."""
|
|
|
|
lru_cache_object.cache_clear()
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
lru_cache_object.cache_clear()
|
|
|
|
|
|
|
|
|
2014-11-29 06:47:53 +08:00
|
|
|
@contextmanager
|
|
|
|
def captured_output(stream_name):
|
|
|
|
"""Return a context manager used by captured_stdout/stdin/stderr
|
|
|
|
that temporarily replaces the sys stream *stream_name* with a StringIO.
|
|
|
|
|
|
|
|
Note: This function and the following ``captured_std*`` are copied
|
|
|
|
from CPython's ``test.support`` module."""
|
|
|
|
orig_stdout = getattr(sys, stream_name)
|
2017-01-07 19:11:46 +08:00
|
|
|
setattr(sys, stream_name, StringIO())
|
2014-11-29 06:47:53 +08:00
|
|
|
try:
|
|
|
|
yield getattr(sys, stream_name)
|
|
|
|
finally:
|
|
|
|
setattr(sys, stream_name, orig_stdout)
|
|
|
|
|
|
|
|
|
|
|
|
def captured_stdout():
|
|
|
|
"""Capture the output of sys.stdout:
|
|
|
|
|
|
|
|
with captured_stdout() as stdout:
|
|
|
|
print("hello")
|
|
|
|
self.assertEqual(stdout.getvalue(), "hello\n")
|
|
|
|
"""
|
|
|
|
return captured_output("stdout")
|
|
|
|
|
|
|
|
|
|
|
|
def captured_stderr():
|
|
|
|
"""Capture the output of sys.stderr:
|
|
|
|
|
|
|
|
with captured_stderr() as stderr:
|
|
|
|
print("hello", file=sys.stderr)
|
|
|
|
self.assertEqual(stderr.getvalue(), "hello\n")
|
|
|
|
"""
|
|
|
|
return captured_output("stderr")
|
|
|
|
|
|
|
|
|
|
|
|
def captured_stdin():
|
|
|
|
"""Capture the input to sys.stdin:
|
|
|
|
|
|
|
|
with captured_stdin() as stdin:
|
|
|
|
stdin.write('hello\n')
|
|
|
|
stdin.seek(0)
|
|
|
|
# call test code that consumes from sys.stdin
|
|
|
|
captured = input()
|
|
|
|
self.assertEqual(captured, "hello")
|
|
|
|
"""
|
|
|
|
return captured_output("stdin")
|
2014-12-06 04:14:20 +08:00
|
|
|
|
|
|
|
|
2014-11-11 02:33:49 +08:00
|
|
|
@contextmanager
|
|
|
|
def freeze_time(t):
|
|
|
|
"""
|
|
|
|
Context manager to temporarily freeze time.time(). This temporarily
|
|
|
|
modifies the time function of the time module. Modules which import the
|
|
|
|
time function directly (e.g. `from time import time`) won't be affected
|
|
|
|
This isn't meant as a public API, but helps reduce some repetitive code in
|
|
|
|
Django's test suite.
|
|
|
|
"""
|
|
|
|
_real_time = time.time
|
|
|
|
time.time = lambda: t
|
|
|
|
try:
|
|
|
|
yield
|
|
|
|
finally:
|
|
|
|
time.time = _real_time
|
2015-01-27 04:57:10 +08:00
|
|
|
|
|
|
|
|
|
|
|
def require_jinja2(test_func):
|
|
|
|
"""
|
|
|
|
Decorator to enable a Jinja2 template engine in addition to the regular
|
|
|
|
Django template engine for a test or skip it if Jinja2 isn't available.
|
|
|
|
"""
|
|
|
|
test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func)
|
|
|
|
test_func = override_settings(TEMPLATES=[{
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
'APP_DIRS': True,
|
|
|
|
}, {
|
|
|
|
'BACKEND': 'django.template.backends.jinja2.Jinja2',
|
|
|
|
'APP_DIRS': True,
|
|
|
|
'OPTIONS': {'keep_trailing_newline': True},
|
|
|
|
}])(test_func)
|
|
|
|
return test_func
|
2015-03-15 18:26:47 +08:00
|
|
|
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
class override_script_prefix(TestContextDecorator):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Decorator or context manager to temporary override the script prefix."""
|
2015-03-15 18:26:47 +08:00
|
|
|
def __init__(self, prefix):
|
|
|
|
self.prefix = prefix
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2015-03-15 18:26:47 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def enable(self):
|
|
|
|
self.old_prefix = get_script_prefix()
|
|
|
|
set_script_prefix(self.prefix)
|
2015-03-15 18:26:47 +08:00
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
def disable(self):
|
|
|
|
set_script_prefix(self.old_prefix)
|
2015-03-24 06:17:43 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class LoggingCaptureMixin:
|
2015-03-24 06:17:43 +08:00
|
|
|
"""
|
|
|
|
Capture the output from the 'django' logger and store it on the class's
|
|
|
|
logger_output attribute.
|
|
|
|
"""
|
|
|
|
def setUp(self):
|
|
|
|
self.logger = logging.getLogger('django')
|
|
|
|
self.old_stream = self.logger.handlers[0].stream
|
2017-01-07 19:11:46 +08:00
|
|
|
self.logger_output = StringIO()
|
2015-03-24 06:17:43 +08:00
|
|
|
self.logger.handlers[0].stream = self.logger_output
|
|
|
|
|
|
|
|
def tearDown(self):
|
|
|
|
self.logger.handlers[0].stream = self.old_stream
|
2015-11-17 13:33:18 +08:00
|
|
|
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
class isolate_apps(TestContextDecorator):
|
2015-11-17 13:33:18 +08:00
|
|
|
"""
|
|
|
|
Act as either a decorator or a context manager to register models defined
|
|
|
|
in its wrapped context to an isolated registry.
|
|
|
|
|
|
|
|
The list of installed apps the isolated registry should contain must be
|
|
|
|
passed as arguments.
|
|
|
|
|
|
|
|
Two optional keyword arguments can be specified:
|
|
|
|
|
|
|
|
`attr_name`: attribute assigned the isolated registry if used as a class
|
|
|
|
decorator.
|
|
|
|
|
2015-11-20 11:27:37 +08:00
|
|
|
`kwarg_name`: keyword argument passing the isolated registry if used as a
|
|
|
|
function decorator.
|
2015-11-17 13:33:18 +08:00
|
|
|
"""
|
|
|
|
def __init__(self, *installed_apps, **kwargs):
|
|
|
|
self.installed_apps = installed_apps
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(**kwargs)
|
2015-11-17 13:33:18 +08:00
|
|
|
|
|
|
|
def enable(self):
|
|
|
|
self.old_apps = Options.default_apps
|
|
|
|
apps = Apps(self.installed_apps)
|
|
|
|
setattr(Options, 'default_apps', apps)
|
|
|
|
return apps
|
|
|
|
|
|
|
|
def disable(self):
|
|
|
|
setattr(Options, 'default_apps', self.old_apps)
|
2015-11-07 21:57:56 +08:00
|
|
|
|
|
|
|
|
|
|
|
def tag(*tags):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Decorator to add tags to a test class or method."""
|
2015-11-07 21:57:56 +08:00
|
|
|
def decorator(obj):
|
|
|
|
setattr(obj, 'tags', set(tags))
|
|
|
|
return obj
|
|
|
|
return decorator
|