2020-03-05 21:26:33 +08:00
|
|
|
import asyncio
|
2012-02-01 04:36:11 +08:00
|
|
|
import difflib
|
2012-04-30 01:58:00 +08:00
|
|
|
import json
|
2013-06-02 01:24:46 +08:00
|
|
|
import posixpath
|
2010-10-12 11:33:19 +08:00
|
|
|
import sys
|
2013-07-01 20:22:27 +08:00
|
|
|
import threading
|
|
|
|
import unittest
|
2015-01-28 20:35:27 +08:00
|
|
|
from collections import Counter
|
2015-07-31 03:00:24 +08:00
|
|
|
from contextlib import contextmanager
|
2015-01-28 20:35:27 +08:00
|
|
|
from copy import copy
|
2018-07-12 12:12:20 +08:00
|
|
|
from difflib import get_close_matches
|
2015-01-28 20:35:27 +08:00
|
|
|
from functools import wraps
|
2016-10-27 05:10:17 +08:00
|
|
|
from unittest.suite import _DebugResult
|
2013-07-01 20:22:27 +08:00
|
|
|
from unittest.util import safe_repr
|
2017-12-20 03:05:10 +08:00
|
|
|
from urllib.parse import (
|
|
|
|
parse_qsl, unquote, urlencode, urljoin, urlparse, urlsplit, urlunparse,
|
|
|
|
)
|
2017-01-07 19:11:46 +08:00
|
|
|
from urllib.request import url2pathname
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2020-03-05 21:26:33 +08:00
|
|
|
from asgiref.sync import async_to_sync
|
|
|
|
|
2013-12-24 19:25:17 +08:00
|
|
|
from django.apps import apps
|
2011-07-13 17:35:51 +08:00
|
|
|
from django.conf import settings
|
2007-08-16 14:06:55 +08:00
|
|
|
from django.core import mail
|
2018-07-12 12:12:20 +08:00
|
|
|
from django.core.exceptions import ImproperlyConfigured, ValidationError
|
2015-02-06 18:38:22 +08:00
|
|
|
from django.core.files import locks
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.core.handlers.wsgi import WSGIHandler, get_path_info
|
2007-08-16 14:06:55 +08:00
|
|
|
from django.core.management import call_command
|
2012-07-25 04:24:16 +08:00
|
|
|
from django.core.management.color import no_style
|
2015-02-28 23:02:20 +08:00
|
|
|
from django.core.management.sql import emit_post_migrate_signal
|
2016-12-07 03:38:43 +08:00
|
|
|
from django.core.servers.basehttp import ThreadedWSGIServer, WSGIRequestHandler
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction
|
2011-08-23 10:32:37 +08:00
|
|
|
from django.forms.fields import CharField
|
2008-07-19 22:46:55 +08:00
|
|
|
from django.http import QueryDict
|
2016-06-04 06:02:38 +08:00
|
|
|
from django.http.request import split_domain_port, validate_host
|
2020-02-13 06:15:00 +08:00
|
|
|
from django.test.client import AsyncClient, Client
|
2012-02-01 04:36:11 +08:00
|
|
|
from django.test.html import HTMLParseError, parse_html
|
2013-12-23 07:10:53 +08:00
|
|
|
from django.test.signals import setting_changed, template_rendered
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.test.utils import (
|
|
|
|
CaptureQueriesContext, ContextList, compare_xml, modify_settings,
|
|
|
|
override_settings,
|
|
|
|
)
|
2019-10-19 03:00:34 +08:00
|
|
|
from django.utils.functional import classproperty
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
from django.views.static import serve
|
2010-10-11 20:55:17 +08:00
|
|
|
|
2013-05-28 04:41:39 +08:00
|
|
|
__all__ = ('TestCase', 'TransactionTestCase',
|
2011-08-13 08:42:08 +08:00
|
|
|
'SimpleTestCase', 'skipIfDBFeature', 'skipUnlessDBFeature')
|
2007-05-05 11:03:33 +08:00
|
|
|
|
2013-03-02 04:29:39 +08:00
|
|
|
|
2007-09-04 07:14:51 +08:00
|
|
|
def to_list(value):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Put value into a list if it's not already one. Return an empty list if
|
|
|
|
value is None.
|
2007-09-04 07:14:51 +08:00
|
|
|
"""
|
|
|
|
if value is None:
|
|
|
|
value = []
|
|
|
|
elif not isinstance(value, list):
|
|
|
|
value = [value]
|
|
|
|
return value
|
|
|
|
|
2014-11-11 04:41:35 +08:00
|
|
|
|
2012-02-01 04:36:11 +08:00
|
|
|
def assert_and_parse_html(self, html, user_msg, msg):
|
|
|
|
try:
|
|
|
|
dom = parse_html(html)
|
2012-04-29 00:09:37 +08:00
|
|
|
except HTMLParseError as e:
|
2016-07-20 22:12:13 +08:00
|
|
|
standardMsg = '%s\n%s' % (msg, e)
|
2012-02-01 04:36:11 +08:00
|
|
|
self.fail(self._formatMessage(user_msg, standardMsg))
|
|
|
|
return dom
|
|
|
|
|
|
|
|
|
2013-03-02 04:29:39 +08:00
|
|
|
class _AssertNumQueriesContext(CaptureQueriesContext):
|
2010-10-12 11:33:19 +08:00
|
|
|
def __init__(self, test_case, num, connection):
|
|
|
|
self.test_case = test_case
|
|
|
|
self.num = num
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__(connection)
|
2010-10-12 11:33:19 +08:00
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__exit__(exc_type, exc_value, traceback)
|
2010-10-12 11:33:19 +08:00
|
|
|
if exc_type is not None:
|
|
|
|
return
|
2013-03-02 04:29:39 +08:00
|
|
|
executed = len(self)
|
2010-10-12 11:33:19 +08:00
|
|
|
self.test_case.assertEqual(
|
2013-12-09 07:07:04 +08:00
|
|
|
executed, self.num,
|
|
|
|
"%d queries executed, %d expected\nCaptured queries were:\n%s" % (
|
|
|
|
executed, self.num,
|
|
|
|
'\n'.join(
|
2017-05-08 15:53:49 +08:00
|
|
|
'%d. %s' % (i, query['sql']) for i, query in enumerate(self.captured_queries, start=1)
|
2013-12-09 07:07:04 +08:00
|
|
|
)
|
2010-10-12 11:33:19 +08:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class _AssertTemplateUsedContext:
|
2012-02-01 03:23:09 +08:00
|
|
|
def __init__(self, test_case, template_name):
|
|
|
|
self.test_case = test_case
|
|
|
|
self.template_name = template_name
|
|
|
|
self.rendered_templates = []
|
|
|
|
self.rendered_template_names = []
|
|
|
|
self.context = ContextList()
|
|
|
|
|
|
|
|
def on_template_render(self, sender, signal, template, context, **kwargs):
|
|
|
|
self.rendered_templates.append(template)
|
|
|
|
self.rendered_template_names.append(template.name)
|
|
|
|
self.context.append(copy(context))
|
|
|
|
|
|
|
|
def test(self):
|
|
|
|
return self.template_name in self.rendered_template_names
|
|
|
|
|
|
|
|
def message(self):
|
2012-06-08 00:08:47 +08:00
|
|
|
return '%s was not rendered.' % self.template_name
|
2012-02-01 03:23:09 +08:00
|
|
|
|
|
|
|
def __enter__(self):
|
|
|
|
template_rendered.connect(self.on_template_render)
|
|
|
|
return self
|
|
|
|
|
|
|
|
def __exit__(self, exc_type, exc_value, traceback):
|
|
|
|
template_rendered.disconnect(self.on_template_render)
|
|
|
|
if exc_type is not None:
|
|
|
|
return
|
2010-10-12 11:33:19 +08:00
|
|
|
|
2012-02-01 03:23:09 +08:00
|
|
|
if not self.test():
|
|
|
|
message = self.message()
|
2017-11-30 00:54:34 +08:00
|
|
|
if self.rendered_templates:
|
2012-06-08 00:08:47 +08:00
|
|
|
message += ' Following templates were rendered: %s' % (
|
2017-11-30 00:54:34 +08:00
|
|
|
', '.join(self.rendered_template_names)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
message += ' No template was rendered.'
|
2012-02-01 03:23:09 +08:00
|
|
|
self.test_case.fail(message)
|
|
|
|
|
|
|
|
|
|
|
|
class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext):
|
|
|
|
def test(self):
|
|
|
|
return self.template_name not in self.rendered_template_names
|
|
|
|
|
|
|
|
def message(self):
|
2012-06-08 00:08:47 +08:00
|
|
|
return '%s was rendered.' % self.template_name
|
2012-02-01 03:23:09 +08:00
|
|
|
|
|
|
|
|
2019-01-13 03:33:50 +08:00
|
|
|
class _DatabaseFailure:
|
2018-07-12 12:12:20 +08:00
|
|
|
def __init__(self, wrapped, message):
|
2015-04-17 04:19:30 +08:00
|
|
|
self.wrapped = wrapped
|
2018-07-12 12:12:20 +08:00
|
|
|
self.message = message
|
2015-04-17 04:19:30 +08:00
|
|
|
|
|
|
|
def __call__(self):
|
2018-07-12 12:12:20 +08:00
|
|
|
raise AssertionError(self.message)
|
|
|
|
|
|
|
|
|
2013-07-01 20:22:27 +08:00
|
|
|
class SimpleTestCase(unittest.TestCase):
|
2013-02-01 01:56:26 +08:00
|
|
|
|
2013-05-19 06:04:34 +08:00
|
|
|
# The class we'll use for the test client self.client.
|
|
|
|
# Can be overridden in derived classes.
|
|
|
|
client_class = Client
|
2020-02-13 06:15:00 +08:00
|
|
|
async_client_class = AsyncClient
|
2013-12-23 19:39:19 +08:00
|
|
|
_overridden_settings = None
|
|
|
|
_modified_settings = None
|
2013-05-19 06:04:34 +08:00
|
|
|
|
2019-09-07 17:57:46 +08:00
|
|
|
databases = set()
|
2018-07-12 12:12:20 +08:00
|
|
|
_disallowed_database_msg = (
|
2019-01-13 03:33:50 +08:00
|
|
|
'Database %(operation)s to %(alias)r are not allowed in SimpleTestCase '
|
|
|
|
'subclasses. Either subclass TestCase or TransactionTestCase to ensure '
|
|
|
|
'proper test isolation or add %(alias)r to %(test)s.databases to silence '
|
2018-07-12 12:12:20 +08:00
|
|
|
'this failure.'
|
|
|
|
)
|
2019-01-13 03:33:50 +08:00
|
|
|
_disallowed_connection_methods = [
|
|
|
|
('connect', 'connections'),
|
|
|
|
('temporary_connection', 'connections'),
|
|
|
|
('cursor', 'queries'),
|
|
|
|
('chunked_cursor', 'queries'),
|
|
|
|
]
|
2015-04-17 04:19:30 +08:00
|
|
|
|
2014-10-19 02:03:10 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUpClass()
|
2014-10-19 02:03:10 +08:00
|
|
|
if cls._overridden_settings:
|
|
|
|
cls._cls_overridden_context = override_settings(**cls._overridden_settings)
|
|
|
|
cls._cls_overridden_context.enable()
|
|
|
|
if cls._modified_settings:
|
|
|
|
cls._cls_modified_context = modify_settings(cls._modified_settings)
|
|
|
|
cls._cls_modified_context.enable()
|
2019-01-13 03:33:50 +08:00
|
|
|
cls._add_databases_failures()
|
2018-07-12 12:12:20 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _validate_databases(cls):
|
|
|
|
if cls.databases == '__all__':
|
|
|
|
return frozenset(connections)
|
|
|
|
for alias in cls.databases:
|
|
|
|
if alias not in connections:
|
|
|
|
message = '%s.%s.databases refers to %r which is not defined in settings.DATABASES.' % (
|
|
|
|
cls.__module__,
|
|
|
|
cls.__qualname__,
|
|
|
|
alias,
|
|
|
|
)
|
|
|
|
close_matches = get_close_matches(alias, list(connections))
|
|
|
|
if close_matches:
|
|
|
|
message += ' Did you mean %r?' % close_matches[0]
|
|
|
|
raise ImproperlyConfigured(message)
|
|
|
|
return frozenset(cls.databases)
|
|
|
|
|
|
|
|
@classmethod
|
2019-01-13 03:33:50 +08:00
|
|
|
def _add_databases_failures(cls):
|
2018-07-12 12:12:20 +08:00
|
|
|
cls.databases = cls._validate_databases()
|
|
|
|
for alias in connections:
|
|
|
|
if alias in cls.databases:
|
|
|
|
continue
|
|
|
|
connection = connections[alias]
|
2019-01-13 03:33:50 +08:00
|
|
|
for name, operation in cls._disallowed_connection_methods:
|
|
|
|
message = cls._disallowed_database_msg % {
|
|
|
|
'test': '%s.%s' % (cls.__module__, cls.__qualname__),
|
|
|
|
'alias': alias,
|
|
|
|
'operation': operation,
|
|
|
|
}
|
|
|
|
method = getattr(connection, name)
|
|
|
|
setattr(connection, name, _DatabaseFailure(method, message))
|
2018-07-12 12:12:20 +08:00
|
|
|
|
|
|
|
@classmethod
|
2019-01-13 03:33:50 +08:00
|
|
|
def _remove_databases_failures(cls):
|
2018-07-12 12:12:20 +08:00
|
|
|
for alias in connections:
|
|
|
|
if alias in cls.databases:
|
|
|
|
continue
|
|
|
|
connection = connections[alias]
|
2019-01-13 03:33:50 +08:00
|
|
|
for name, _ in cls._disallowed_connection_methods:
|
|
|
|
method = getattr(connection, name)
|
|
|
|
setattr(connection, name, method.wrapped)
|
2014-10-19 02:03:10 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2019-01-13 03:33:50 +08:00
|
|
|
cls._remove_databases_failures()
|
2014-10-19 02:03:10 +08:00
|
|
|
if hasattr(cls, '_cls_modified_context'):
|
|
|
|
cls._cls_modified_context.disable()
|
|
|
|
delattr(cls, '_cls_modified_context')
|
|
|
|
if hasattr(cls, '_cls_overridden_context'):
|
|
|
|
cls._cls_overridden_context.disable()
|
|
|
|
delattr(cls, '_cls_overridden_context')
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDownClass()
|
2014-10-19 02:03:10 +08:00
|
|
|
|
2012-11-25 06:47:41 +08:00
|
|
|
def __call__(self, result=None):
|
|
|
|
"""
|
|
|
|
Wrapper around default __call__ method to perform common Django test
|
|
|
|
set up. This means that user-defined Test Cases aren't required to
|
|
|
|
include a call to super().setUp().
|
|
|
|
"""
|
2016-10-27 05:10:17 +08:00
|
|
|
self._setup_and_call(result)
|
|
|
|
|
|
|
|
def debug(self):
|
|
|
|
"""Perform the same as __call__(), without catching the exception."""
|
|
|
|
debug_result = _DebugResult()
|
|
|
|
self._setup_and_call(debug_result, debug=True)
|
|
|
|
|
|
|
|
def _setup_and_call(self, result, debug=False):
|
|
|
|
"""
|
|
|
|
Perform the following in order: pre-setup, run test, post-teardown,
|
|
|
|
skipping pre/post hooks if test is set to be skipped.
|
|
|
|
|
|
|
|
If debug=True, reraise any errors in setup and use super().debug()
|
|
|
|
instead of __call__() to run the test.
|
|
|
|
"""
|
2012-11-25 06:47:41 +08:00
|
|
|
testMethod = getattr(self, self._testMethodName)
|
2016-03-29 06:33:29 +08:00
|
|
|
skipped = (
|
|
|
|
getattr(self.__class__, "__unittest_skip__", False) or
|
|
|
|
getattr(testMethod, "__unittest_skip__", False)
|
|
|
|
)
|
2012-11-25 06:47:41 +08:00
|
|
|
|
2020-03-05 21:26:33 +08:00
|
|
|
# Convert async test methods.
|
|
|
|
if asyncio.iscoroutinefunction(testMethod):
|
|
|
|
setattr(self, self._testMethodName, async_to_sync(testMethod))
|
|
|
|
|
2012-11-25 06:47:41 +08:00
|
|
|
if not skipped:
|
|
|
|
try:
|
|
|
|
self._pre_setup()
|
|
|
|
except Exception:
|
2016-10-27 05:10:17 +08:00
|
|
|
if debug:
|
|
|
|
raise
|
2012-11-25 06:47:41 +08:00
|
|
|
result.addError(self, sys.exc_info())
|
|
|
|
return
|
2016-10-27 05:10:17 +08:00
|
|
|
if debug:
|
|
|
|
super().debug()
|
|
|
|
else:
|
|
|
|
super().__call__(result)
|
2012-11-25 06:47:41 +08:00
|
|
|
if not skipped:
|
|
|
|
try:
|
|
|
|
self._post_teardown()
|
|
|
|
except Exception:
|
2016-10-27 05:10:17 +08:00
|
|
|
if debug:
|
|
|
|
raise
|
2012-11-25 06:47:41 +08:00
|
|
|
result.addError(self, sys.exc_info())
|
|
|
|
return
|
|
|
|
|
|
|
|
def _pre_setup(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
Perform pre-test setup:
|
|
|
|
* Create a test client.
|
|
|
|
* Clear the mail test outbox.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
|
|
|
self.client = self.client_class()
|
2020-02-13 06:15:00 +08:00
|
|
|
self.async_client = self.async_client_class()
|
2013-05-19 06:04:34 +08:00
|
|
|
mail.outbox = []
|
|
|
|
|
2012-11-25 06:47:41 +08:00
|
|
|
def _post_teardown(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Perform post-test things."""
|
2015-08-19 00:07:13 +08:00
|
|
|
pass
|
2012-11-25 06:47:41 +08:00
|
|
|
|
2011-08-13 08:42:08 +08:00
|
|
|
def settings(self, **kwargs):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
A context manager that temporarily sets a setting and reverts to the
|
|
|
|
original value when exiting the context.
|
2011-08-13 08:42:08 +08:00
|
|
|
"""
|
|
|
|
return override_settings(**kwargs)
|
|
|
|
|
2013-12-23 19:39:19 +08:00
|
|
|
def modify_settings(self, **kwargs):
|
|
|
|
"""
|
|
|
|
A context manager that temporarily applies changes a list setting and
|
|
|
|
reverts back to the original value when exiting the context.
|
|
|
|
"""
|
|
|
|
return modify_settings(**kwargs)
|
|
|
|
|
2007-09-04 08:50:06 +08:00
|
|
|
def assertRedirects(self, response, expected_url, status_code=302,
|
2016-12-17 07:13:34 +08:00
|
|
|
target_status_code=200, msg_prefix='',
|
2013-09-08 05:13:57 +08:00
|
|
|
fetch_redirect_response=True):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
Assert that a response redirected to a specific URL and that the
|
2007-05-05 11:03:33 +08:00
|
|
|
redirect URL can be loaded.
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2017-09-09 21:41:45 +08:00
|
|
|
Won't work for external links since it uses the test client to do a
|
|
|
|
request (use fetch_redirect_response=False to check such links without
|
|
|
|
fetching them).
|
2007-05-05 11:03:33 +08:00
|
|
|
"""
|
2010-01-22 23:02:02 +08:00
|
|
|
if msg_prefix:
|
|
|
|
msg_prefix += ": "
|
|
|
|
|
2009-02-27 21:14:59 +08:00
|
|
|
if hasattr(response, 'redirect_chain'):
|
|
|
|
# The request was a followed redirect
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(
|
2017-11-30 00:54:34 +08:00
|
|
|
response.redirect_chain,
|
2016-03-29 06:33:29 +08:00
|
|
|
msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)"
|
|
|
|
% (response.status_code, status_code)
|
|
|
|
)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
response.redirect_chain[0][1], status_code,
|
|
|
|
msg_prefix + "Initial response didn't redirect as expected: Response code was %d (expected %d)"
|
|
|
|
% (response.redirect_chain[0][1], status_code)
|
|
|
|
)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
|
|
|
url, status_code = response.redirect_chain[-1]
|
2013-10-29 03:34:09 +08:00
|
|
|
scheme, netloc, path, query, fragment = urlsplit(url)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
response.status_code, target_status_code,
|
|
|
|
msg_prefix + "Response didn't redirect as expected: Final Response code was %d (expected %d)"
|
|
|
|
% (response.status_code, target_status_code)
|
|
|
|
)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
|
|
|
else:
|
|
|
|
# Not a followed redirect
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
response.status_code, status_code,
|
|
|
|
msg_prefix + "Response didn't redirect as expected: Response code was %d (expected %d)"
|
|
|
|
% (response.status_code, status_code)
|
|
|
|
)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2013-02-13 16:55:43 +08:00
|
|
|
url = response.url
|
2009-02-27 21:14:59 +08:00
|
|
|
scheme, netloc, path, query, fragment = urlsplit(url)
|
|
|
|
|
2016-04-02 22:35:33 +08:00
|
|
|
# Prepend the request path to handle relative path redirects.
|
|
|
|
if not path.startswith('/'):
|
|
|
|
url = urljoin(response.request['PATH_INFO'], url)
|
|
|
|
path = urljoin(response.request['PATH_INFO'], path)
|
|
|
|
|
2013-09-08 05:13:57 +08:00
|
|
|
if fetch_redirect_response:
|
2016-06-03 12:47:30 +08:00
|
|
|
# netloc might be empty, or in cases where Django tests the
|
|
|
|
# HTTP scheme, the convention is for netloc to be 'testserver'.
|
|
|
|
# Trust both as "internal" URLs here.
|
2016-06-04 06:02:38 +08:00
|
|
|
domain, port = split_domain_port(netloc)
|
|
|
|
if domain and not validate_host(domain, settings.ALLOWED_HOSTS):
|
2016-06-03 04:00:04 +08:00
|
|
|
raise ValueError(
|
2016-06-04 06:02:38 +08:00
|
|
|
"The test client is unable to fetch remote URLs (got %s). "
|
|
|
|
"If the host is served by Django, add '%s' to ALLOWED_HOSTS. "
|
|
|
|
"Otherwise, use assertRedirects(..., fetch_redirect_response=False)."
|
|
|
|
% (url, domain)
|
2016-06-03 04:00:04 +08:00
|
|
|
)
|
2013-09-08 05:13:57 +08:00
|
|
|
# Get the redirection page, using the same client that was used
|
|
|
|
# to obtain the original response.
|
2017-08-18 08:10:10 +08:00
|
|
|
extra = response.client.extra or {}
|
|
|
|
redirect_response = response.client.get(
|
|
|
|
path,
|
|
|
|
QueryDict(query),
|
|
|
|
secure=(scheme == 'https'),
|
|
|
|
**extra,
|
|
|
|
)
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
redirect_response.status_code, target_status_code,
|
|
|
|
msg_prefix + "Couldn't retrieve redirection page '%s': response code was %d (expected %d)"
|
|
|
|
% (path, redirect_response.status_code, target_status_code)
|
|
|
|
)
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2017-12-20 03:05:10 +08:00
|
|
|
self.assertURLEqual(
|
2016-03-29 06:33:29 +08:00
|
|
|
url, expected_url,
|
|
|
|
msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url)
|
|
|
|
)
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2017-12-20 03:05:10 +08:00
|
|
|
def assertURLEqual(self, url1, url2, msg_prefix=''):
|
|
|
|
"""
|
|
|
|
Assert that two URLs are the same, ignoring the order of query string
|
|
|
|
parameters except for parameters with the same name.
|
|
|
|
|
|
|
|
For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but
|
|
|
|
/path/?a=1&a=2 isn't equal to /path/?a=2&a=1.
|
|
|
|
"""
|
|
|
|
def normalize(url):
|
|
|
|
"""Sort the URL's query string parameters."""
|
2019-01-21 22:31:33 +08:00
|
|
|
url = str(url) # Coerce reverse_lazy() URLs.
|
2017-12-20 03:05:10 +08:00
|
|
|
scheme, netloc, path, params, query, fragment = urlparse(url)
|
|
|
|
query_parts = sorted(parse_qsl(query))
|
|
|
|
return urlunparse((scheme, netloc, path, params, urlencode(query_parts), fragment))
|
|
|
|
|
|
|
|
self.assertEqual(
|
|
|
|
normalize(url1), normalize(url2),
|
|
|
|
msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2)
|
|
|
|
)
|
|
|
|
|
2013-08-23 01:54:26 +08:00
|
|
|
def _assert_contains(self, response, text, status_code, msg_prefix, html):
|
2011-10-22 17:15:50 +08:00
|
|
|
# If the response supports deferred rendering and hasn't been rendered
|
|
|
|
# yet, then ensure that it does get rendered before proceeding further.
|
2016-04-04 08:37:32 +08:00
|
|
|
if hasattr(response, 'render') and callable(response.render) and not response.is_rendered:
|
2011-10-22 17:15:50 +08:00
|
|
|
response.render()
|
|
|
|
|
2010-01-22 23:02:02 +08:00
|
|
|
if msg_prefix:
|
|
|
|
msg_prefix += ": "
|
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
response.status_code, status_code,
|
2010-08-07 00:54:17 +08:00
|
|
|
msg_prefix + "Couldn't retrieve content: Response code was %d"
|
2016-03-29 06:33:29 +08:00
|
|
|
" (expected %d)" % (response.status_code, status_code)
|
|
|
|
)
|
2013-04-11 16:36:12 +08:00
|
|
|
|
2012-10-24 17:33:56 +08:00
|
|
|
if response.streaming:
|
|
|
|
content = b''.join(response.streaming_content)
|
|
|
|
else:
|
|
|
|
content = response.content
|
2013-04-11 16:36:12 +08:00
|
|
|
if not isinstance(text, bytes) or html:
|
2018-02-11 00:44:39 +08:00
|
|
|
text = str(text)
|
2013-11-17 01:54:12 +08:00
|
|
|
content = content.decode(response.charset)
|
2013-04-13 02:00:49 +08:00
|
|
|
text_repr = "'%s'" % text
|
|
|
|
else:
|
|
|
|
text_repr = repr(text)
|
2012-02-01 04:36:11 +08:00
|
|
|
if html:
|
2016-03-29 06:33:29 +08:00
|
|
|
content = assert_and_parse_html(self, content, None, "Response's content is not valid HTML:")
|
|
|
|
text = assert_and_parse_html(self, text, None, "Second argument is not valid HTML:")
|
2012-08-14 18:19:17 +08:00
|
|
|
real_count = content.count(text)
|
2013-08-23 01:54:26 +08:00
|
|
|
return (text_repr, real_count, msg_prefix)
|
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
|
2013-08-23 01:54:26 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that a response indicates that some content was retrieved
|
|
|
|
successfully, (i.e., the HTTP status code was as expected) and that
|
2013-08-23 01:54:26 +08:00
|
|
|
``text`` occurs ``count`` times in the content of the response.
|
|
|
|
If ``count`` is None, the count doesn't matter - the assertion is true
|
|
|
|
if the text occurs at least once in the response.
|
|
|
|
"""
|
|
|
|
text_repr, real_count, msg_prefix = self._assert_contains(
|
|
|
|
response, text, status_code, msg_prefix, html)
|
|
|
|
|
2007-07-21 12:36:28 +08:00
|
|
|
if count is not None:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
real_count, count,
|
|
|
|
msg_prefix + "Found %d instances of %s in response (expected %d)" % (real_count, text_repr, count)
|
|
|
|
)
|
2007-07-20 22:32:20 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(real_count != 0, msg_prefix + "Couldn't find %s in response" % text_repr)
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
def assertNotContains(self, response, text, status_code=200, msg_prefix='', html=False):
|
2008-06-06 21:50:02 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that a response indicates that some content was retrieved
|
|
|
|
successfully, (i.e., the HTTP status code was as expected) and that
|
2008-06-06 21:50:02 +08:00
|
|
|
``text`` doesn't occurs in the content of the response.
|
|
|
|
"""
|
2013-08-23 01:54:26 +08:00
|
|
|
text_repr, real_count, msg_prefix = self._assert_contains(
|
|
|
|
response, text, status_code, msg_prefix, html)
|
2011-10-22 17:15:50 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr)
|
2008-06-06 21:50:02 +08:00
|
|
|
|
2010-01-22 23:02:02 +08:00
|
|
|
def assertFormError(self, response, form, field, errors, msg_prefix=''):
|
2007-09-04 08:50:06 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that a form used to render the response has a specific field
|
2007-09-04 08:50:06 +08:00
|
|
|
error.
|
|
|
|
"""
|
2010-01-22 23:02:02 +08:00
|
|
|
if msg_prefix:
|
|
|
|
msg_prefix += ": "
|
|
|
|
|
2007-09-04 07:14:51 +08:00
|
|
|
# Put context(s) into a list to simplify processing.
|
2007-09-04 08:50:06 +08:00
|
|
|
contexts = to_list(response.context)
|
2007-09-04 07:14:51 +08:00
|
|
|
if not contexts:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(msg_prefix + "Response did not use any contexts to render the response")
|
2007-05-07 20:34:18 +08:00
|
|
|
|
2007-09-04 07:14:51 +08:00
|
|
|
# Put error(s) into a list to simplify processing.
|
|
|
|
errors = to_list(errors)
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2007-05-07 20:34:18 +08:00
|
|
|
# Search all contexts for the error.
|
|
|
|
found_form = False
|
2013-10-27 01:50:40 +08:00
|
|
|
for i, context in enumerate(contexts):
|
2007-09-04 08:50:06 +08:00
|
|
|
if form not in context:
|
|
|
|
continue
|
|
|
|
found_form = True
|
|
|
|
for err in errors:
|
|
|
|
if field:
|
|
|
|
if field in context[form].errors:
|
|
|
|
field_errors = context[form].errors[field]
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(
|
|
|
|
err in field_errors,
|
2010-01-22 23:02:02 +08:00
|
|
|
msg_prefix + "The field '%s' on form '%s' in"
|
|
|
|
" context %d does not contain the error '%s'"
|
|
|
|
" (actual errors: %s)" %
|
2016-03-29 06:33:29 +08:00
|
|
|
(field, form, i, err, repr(field_errors))
|
|
|
|
)
|
2007-09-04 08:50:06 +08:00
|
|
|
elif field in context[form].fields:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(
|
|
|
|
msg_prefix + "The field '%s' on form '%s' in context %d contains no errors" %
|
|
|
|
(field, form, i)
|
|
|
|
)
|
2007-05-10 21:48:18 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(
|
|
|
|
msg_prefix + "The form '%s' in context %d does not contain the field '%s'" %
|
|
|
|
(form, i, field)
|
|
|
|
)
|
2007-09-04 08:50:06 +08:00
|
|
|
else:
|
|
|
|
non_field_errors = context[form].non_field_errors()
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(
|
|
|
|
err in non_field_errors,
|
2010-01-22 23:02:02 +08:00
|
|
|
msg_prefix + "The form '%s' in context %d does not"
|
|
|
|
" contain the non-field error '%s'"
|
|
|
|
" (actual errors: %s)" %
|
2018-03-30 16:42:45 +08:00
|
|
|
(form, i, err, non_field_errors or 'none')
|
2016-03-29 06:33:29 +08:00
|
|
|
)
|
2007-05-07 20:34:18 +08:00
|
|
|
if not found_form:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(msg_prefix + "The form '%s' was not used to render the response" % form)
|
2007-09-04 08:50:06 +08:00
|
|
|
|
2013-02-09 07:45:26 +08:00
|
|
|
def assertFormsetError(self, response, formset, form_index, field, errors,
|
|
|
|
msg_prefix=''):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that a formset used to render the response has a specific error.
|
2013-02-09 07:45:26 +08:00
|
|
|
|
|
|
|
For field errors, specify the ``form_index`` and the ``field``.
|
|
|
|
For non-field errors, specify the ``form_index`` and the ``field`` as
|
|
|
|
None.
|
|
|
|
For non-form errors, specify ``form_index`` as None and the ``field``
|
|
|
|
as None.
|
|
|
|
"""
|
|
|
|
# Add punctuation to msg_prefix
|
|
|
|
if msg_prefix:
|
|
|
|
msg_prefix += ": "
|
|
|
|
|
|
|
|
# Put context(s) into a list to simplify processing.
|
|
|
|
contexts = to_list(response.context)
|
|
|
|
if not contexts:
|
|
|
|
self.fail(msg_prefix + 'Response did not use any contexts to '
|
|
|
|
'render the response')
|
|
|
|
|
|
|
|
# Put error(s) into a list to simplify processing.
|
|
|
|
errors = to_list(errors)
|
|
|
|
|
|
|
|
# Search all contexts for the error.
|
|
|
|
found_formset = False
|
|
|
|
for i, context in enumerate(contexts):
|
|
|
|
if formset not in context:
|
|
|
|
continue
|
|
|
|
found_formset = True
|
|
|
|
for err in errors:
|
|
|
|
if field is not None:
|
|
|
|
if field in context[formset].forms[form_index].errors:
|
|
|
|
field_errors = context[formset].forms[form_index].errors[field]
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(
|
|
|
|
err in field_errors,
|
|
|
|
msg_prefix + "The field '%s' on formset '%s', "
|
|
|
|
"form %d in context %d does not contain the "
|
|
|
|
"error '%s' (actual errors: %s)" %
|
|
|
|
(field, formset, form_index, i, err, repr(field_errors))
|
|
|
|
)
|
2013-02-09 07:45:26 +08:00
|
|
|
elif field in context[formset].forms[form_index].fields:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(
|
|
|
|
msg_prefix + "The field '%s' on formset '%s', form %d in context %d contains no errors"
|
|
|
|
% (field, formset, form_index, i)
|
|
|
|
)
|
2013-02-09 07:45:26 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(
|
|
|
|
msg_prefix + "The formset '%s', form %d in context %d does not contain the field '%s'"
|
|
|
|
% (formset, form_index, i, field)
|
|
|
|
)
|
2013-02-09 07:45:26 +08:00
|
|
|
elif form_index is not None:
|
|
|
|
non_field_errors = context[formset].forms[form_index].non_field_errors()
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertFalse(
|
2017-11-30 00:54:34 +08:00
|
|
|
not non_field_errors,
|
2016-03-29 06:33:29 +08:00
|
|
|
msg_prefix + "The formset '%s', form %d in context %d "
|
|
|
|
"does not contain any non-field errors." % (formset, form_index, i)
|
|
|
|
)
|
|
|
|
self.assertTrue(
|
|
|
|
err in non_field_errors,
|
|
|
|
msg_prefix + "The formset '%s', form %d in context %d "
|
|
|
|
"does not contain the non-field error '%s' (actual errors: %s)"
|
|
|
|
% (formset, form_index, i, err, repr(non_field_errors))
|
|
|
|
)
|
2013-02-09 07:45:26 +08:00
|
|
|
else:
|
|
|
|
non_form_errors = context[formset].non_form_errors()
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertFalse(
|
2017-11-30 00:54:34 +08:00
|
|
|
not non_form_errors,
|
2016-03-29 06:33:29 +08:00
|
|
|
msg_prefix + "The formset '%s' in context %d does not "
|
|
|
|
"contain any non-form errors." % (formset, i)
|
|
|
|
)
|
|
|
|
self.assertTrue(
|
|
|
|
err in non_form_errors,
|
|
|
|
msg_prefix + "The formset '%s' in context %d does not "
|
|
|
|
"contain the non-form error '%s' (actual errors: %s)"
|
|
|
|
% (formset, i, err, repr(non_form_errors))
|
|
|
|
)
|
2013-02-09 07:45:26 +08:00
|
|
|
if not found_formset:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.fail(msg_prefix + "The formset '%s' was not used to render the response" % formset)
|
2013-02-09 07:45:26 +08:00
|
|
|
|
2013-08-23 01:54:26 +08:00
|
|
|
def _assert_template_used(self, response, template_name, msg_prefix):
|
|
|
|
|
2012-02-01 03:23:09 +08:00
|
|
|
if response is None and template_name is None:
|
2012-06-08 00:08:47 +08:00
|
|
|
raise TypeError('response and/or template_name argument must be provided')
|
2012-02-01 03:23:09 +08:00
|
|
|
|
2010-01-22 23:02:02 +08:00
|
|
|
if msg_prefix:
|
|
|
|
msg_prefix += ": "
|
|
|
|
|
2014-10-12 00:53:29 +08:00
|
|
|
if template_name is not None and response is not None and not hasattr(response, 'templates'):
|
|
|
|
raise ValueError(
|
|
|
|
"assertTemplateUsed() and assertTemplateNotUsed() are only "
|
|
|
|
"usable on responses fetched using the Django test Client."
|
|
|
|
)
|
|
|
|
|
2012-02-01 03:23:09 +08:00
|
|
|
if not hasattr(response, 'templates') or (response is None and template_name):
|
|
|
|
if response:
|
|
|
|
template_name = response
|
|
|
|
response = None
|
2013-08-23 01:54:26 +08:00
|
|
|
# use this template with context manager
|
|
|
|
return template_name, None, msg_prefix
|
2012-02-01 03:23:09 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
template_names = [t.name for t in response.templates if t.name is not None]
|
2013-08-23 01:54:26 +08:00
|
|
|
return None, template_names, msg_prefix
|
|
|
|
|
2014-04-15 03:13:49 +08:00
|
|
|
def assertTemplateUsed(self, response=None, template_name=None, msg_prefix='', count=None):
|
2013-08-23 01:54:26 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that the template with the provided name was used in rendering
|
2013-08-23 01:54:26 +08:00
|
|
|
the response. Also usable as context manager.
|
|
|
|
"""
|
|
|
|
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
|
|
|
|
response, template_name, msg_prefix)
|
|
|
|
|
|
|
|
if context_mgr_template:
|
|
|
|
# Use assertTemplateUsed as context manager.
|
|
|
|
return _AssertTemplateUsedContext(self, context_mgr_template)
|
|
|
|
|
2007-09-04 07:14:51 +08:00
|
|
|
if not template_names:
|
2010-01-22 23:02:02 +08:00
|
|
|
self.fail(msg_prefix + "No templates used to render the response")
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(
|
|
|
|
template_name in template_names,
|
2010-01-22 23:02:02 +08:00
|
|
|
msg_prefix + "Template '%s' was not a template used to render"
|
2016-03-29 06:33:29 +08:00
|
|
|
" the response. Actual template(s) used: %s"
|
|
|
|
% (template_name, ', '.join(template_names))
|
|
|
|
)
|
2007-05-07 20:34:18 +08:00
|
|
|
|
2014-04-15 03:13:49 +08:00
|
|
|
if count is not None:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
template_names.count(template_name), count,
|
2014-04-15 03:13:49 +08:00
|
|
|
msg_prefix + "Template '%s' was expected to be rendered %d "
|
2016-03-29 06:33:29 +08:00
|
|
|
"time(s) but was actually rendered %d time(s)."
|
|
|
|
% (template_name, count, template_names.count(template_name))
|
|
|
|
)
|
2014-04-15 03:13:49 +08:00
|
|
|
|
2012-02-01 03:23:09 +08:00
|
|
|
def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=''):
|
2007-09-04 08:50:06 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that the template with the provided name was NOT used in
|
2012-02-04 04:45:45 +08:00
|
|
|
rendering the response. Also usable as context manager.
|
2007-09-04 08:50:06 +08:00
|
|
|
"""
|
2013-08-23 01:54:26 +08:00
|
|
|
context_mgr_template, template_names, msg_prefix = self._assert_template_used(
|
2016-03-29 06:33:29 +08:00
|
|
|
response, template_name, msg_prefix
|
|
|
|
)
|
2013-08-23 01:54:26 +08:00
|
|
|
if context_mgr_template:
|
|
|
|
# Use assertTemplateNotUsed as context manager.
|
|
|
|
return _AssertTemplateNotUsedContext(self, context_mgr_template)
|
2012-02-01 03:23:09 +08:00
|
|
|
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertFalse(
|
|
|
|
template_name in template_names,
|
|
|
|
msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name
|
|
|
|
)
|
2009-01-16 10:30:22 +08:00
|
|
|
|
2015-07-31 03:00:24 +08:00
|
|
|
@contextmanager
|
2018-04-28 05:18:15 +08:00
|
|
|
def _assert_raises_or_warns_cm(self, func, cm_attr, expected_exception, expected_message):
|
|
|
|
with func(expected_exception) as cm:
|
2015-07-31 03:00:24 +08:00
|
|
|
yield cm
|
2018-04-28 05:18:15 +08:00
|
|
|
self.assertIn(expected_message, str(getattr(cm, cm_attr)))
|
|
|
|
|
|
|
|
def _assertFooMessage(self, func, cm_attr, expected_exception, expected_message, *args, **kwargs):
|
|
|
|
callable_obj = None
|
|
|
|
if args:
|
2018-09-28 21:57:12 +08:00
|
|
|
callable_obj, *args = args
|
2018-04-28 05:18:15 +08:00
|
|
|
cm = self._assert_raises_or_warns_cm(func, cm_attr, expected_exception, expected_message)
|
|
|
|
# Assertion used in context manager fashion.
|
|
|
|
if callable_obj is None:
|
|
|
|
return cm
|
|
|
|
# Assertion was passed a callable.
|
|
|
|
with cm:
|
|
|
|
callable_obj(*args, **kwargs)
|
2015-07-31 03:00:24 +08:00
|
|
|
|
2015-05-10 07:13:05 +08:00
|
|
|
def assertRaisesMessage(self, expected_exception, expected_message, *args, **kwargs):
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
2018-07-18 23:54:15 +08:00
|
|
|
Assert that expected_message is found in the message of a raised
|
2015-07-31 03:00:24 +08:00
|
|
|
exception.
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
Args:
|
|
|
|
expected_exception: Exception class expected to be raised.
|
|
|
|
expected_message: expected error message string value.
|
2015-05-10 07:13:05 +08:00
|
|
|
args: Function to be called and extra positional args.
|
2013-05-19 06:04:34 +08:00
|
|
|
kwargs: Extra kwargs.
|
|
|
|
"""
|
2018-04-28 05:18:15 +08:00
|
|
|
return self._assertFooMessage(
|
|
|
|
self.assertRaises, 'exception', expected_exception, expected_message,
|
|
|
|
*args, **kwargs
|
|
|
|
)
|
2015-07-31 03:00:24 +08:00
|
|
|
|
2018-04-28 05:18:15 +08:00
|
|
|
def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs):
|
|
|
|
"""
|
|
|
|
Same as assertRaisesMessage but for assertWarns() instead of
|
|
|
|
assertRaises().
|
|
|
|
"""
|
|
|
|
return self._assertFooMessage(
|
|
|
|
self.assertWarns, 'warning', expected_warning, expected_message,
|
|
|
|
*args, **kwargs
|
|
|
|
)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def assertFieldOutput(self, fieldclass, valid, invalid, field_args=None,
|
2016-03-29 06:33:29 +08:00
|
|
|
field_kwargs=None, empty_value=''):
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that a form field behaves correctly with various inputs.
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
Args:
|
|
|
|
fieldclass: the class of the field to be tested.
|
|
|
|
valid: a dictionary mapping valid inputs to their expected
|
|
|
|
cleaned values.
|
|
|
|
invalid: a dictionary mapping invalid inputs to one or more
|
|
|
|
raised error messages.
|
|
|
|
field_args: the args passed to instantiate the field
|
|
|
|
field_kwargs: the kwargs passed to instantiate the field
|
|
|
|
empty_value: the expected clean output for inputs in empty_values
|
|
|
|
"""
|
|
|
|
if field_args is None:
|
|
|
|
field_args = []
|
|
|
|
if field_kwargs is None:
|
|
|
|
field_kwargs = {}
|
|
|
|
required = fieldclass(*field_args, **field_kwargs)
|
2017-12-11 20:08:45 +08:00
|
|
|
optional = fieldclass(*field_args, **{**field_kwargs, 'required': False})
|
2013-05-19 06:04:34 +08:00
|
|
|
# test valid inputs
|
|
|
|
for input, output in valid.items():
|
|
|
|
self.assertEqual(required.clean(input), output)
|
|
|
|
self.assertEqual(optional.clean(input), output)
|
|
|
|
# test invalid inputs
|
|
|
|
for input, errors in invalid.items():
|
|
|
|
with self.assertRaises(ValidationError) as context_manager:
|
|
|
|
required.clean(input)
|
|
|
|
self.assertEqual(context_manager.exception.messages, errors)
|
|
|
|
|
|
|
|
with self.assertRaises(ValidationError) as context_manager:
|
|
|
|
optional.clean(input)
|
|
|
|
self.assertEqual(context_manager.exception.messages, errors)
|
|
|
|
# test required inputs
|
2018-02-11 00:44:39 +08:00
|
|
|
error_required = [required.error_messages['required']]
|
2013-05-19 06:04:34 +08:00
|
|
|
for e in required.empty_values:
|
|
|
|
with self.assertRaises(ValidationError) as context_manager:
|
|
|
|
required.clean(e)
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(context_manager.exception.messages, error_required)
|
2013-05-19 06:04:34 +08:00
|
|
|
self.assertEqual(optional.clean(e), empty_value)
|
|
|
|
# test that max_length and min_length are always accepted
|
|
|
|
if issubclass(fieldclass, CharField):
|
2013-10-27 01:50:40 +08:00
|
|
|
field_kwargs.update({'min_length': 2, 'max_length': 20})
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertIsInstance(fieldclass(*field_args, **field_kwargs), fieldclass)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def assertHTMLEqual(self, html1, html2, msg=None):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that two HTML snippets are semantically the same.
|
2013-05-19 06:04:34 +08:00
|
|
|
Whitespace in most cases is ignored, and attribute ordering is not
|
2017-01-25 04:37:33 +08:00
|
|
|
significant. The arguments must be valid HTML.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
2016-03-29 06:33:29 +08:00
|
|
|
dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
|
|
|
|
dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
if dom1 != dom2:
|
|
|
|
standardMsg = '%s != %s' % (
|
|
|
|
safe_repr(dom1, True), safe_repr(dom2, True))
|
|
|
|
diff = ('\n' + '\n'.join(difflib.ndiff(
|
2016-12-29 23:27:49 +08:00
|
|
|
str(dom1).splitlines(), str(dom2).splitlines(),
|
2016-03-29 06:33:29 +08:00
|
|
|
)))
|
2013-05-19 06:04:34 +08:00
|
|
|
standardMsg = self._truncateMessage(standardMsg, diff)
|
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
|
|
|
|
def assertHTMLNotEqual(self, html1, html2, msg=None):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Assert that two HTML snippets are not semantically equivalent."""
|
2016-03-29 06:33:29 +08:00
|
|
|
dom1 = assert_and_parse_html(self, html1, msg, 'First argument is not valid HTML:')
|
|
|
|
dom2 = assert_and_parse_html(self, html2, msg, 'Second argument is not valid HTML:')
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
if dom1 == dom2:
|
|
|
|
standardMsg = '%s == %s' % (
|
|
|
|
safe_repr(dom1, True), safe_repr(dom2, True))
|
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
|
|
|
|
def assertInHTML(self, needle, haystack, count=None, msg_prefix=''):
|
2016-03-29 06:33:29 +08:00
|
|
|
needle = assert_and_parse_html(self, needle, None, 'First argument is not valid HTML:')
|
|
|
|
haystack = assert_and_parse_html(self, haystack, None, 'Second argument is not valid HTML:')
|
2013-05-19 06:04:34 +08:00
|
|
|
real_count = haystack.count(needle)
|
|
|
|
if count is not None:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertEqual(
|
|
|
|
real_count, count,
|
|
|
|
msg_prefix + "Found %d instances of '%s' in response (expected %d)" % (real_count, needle, count)
|
|
|
|
)
|
2013-05-19 06:04:34 +08:00
|
|
|
else:
|
2016-03-29 06:33:29 +08:00
|
|
|
self.assertTrue(real_count != 0, msg_prefix + "Couldn't find '%s' in response" % needle)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def assertJSONEqual(self, raw, expected_data, msg=None):
|
2014-04-17 17:44:30 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that the JSON fragments raw and expected_data are equal.
|
2014-04-17 17:44:30 +08:00
|
|
|
Usual JSON non-significant whitespace rules apply as the heavyweight
|
|
|
|
is delegated to the json library.
|
|
|
|
"""
|
2013-05-19 06:04:34 +08:00
|
|
|
try:
|
|
|
|
data = json.loads(raw)
|
2017-06-21 03:16:37 +08:00
|
|
|
except json.JSONDecodeError:
|
2013-05-19 06:04:34 +08:00
|
|
|
self.fail("First argument is not valid JSON: %r" % raw)
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(expected_data, str):
|
2013-05-19 06:04:34 +08:00
|
|
|
try:
|
|
|
|
expected_data = json.loads(expected_data)
|
|
|
|
except ValueError:
|
|
|
|
self.fail("Second argument is not valid JSON: %r" % expected_data)
|
|
|
|
self.assertEqual(data, expected_data, msg=msg)
|
|
|
|
|
2014-04-17 17:44:30 +08:00
|
|
|
def assertJSONNotEqual(self, raw, expected_data, msg=None):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that the JSON fragments raw and expected_data are not equal.
|
2014-04-17 17:44:30 +08:00
|
|
|
Usual JSON non-significant whitespace rules apply as the heavyweight
|
|
|
|
is delegated to the json library.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
data = json.loads(raw)
|
2017-06-21 03:16:37 +08:00
|
|
|
except json.JSONDecodeError:
|
2014-04-17 17:44:30 +08:00
|
|
|
self.fail("First argument is not valid JSON: %r" % raw)
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(expected_data, str):
|
2014-04-17 17:44:30 +08:00
|
|
|
try:
|
|
|
|
expected_data = json.loads(expected_data)
|
2017-06-21 03:16:37 +08:00
|
|
|
except json.JSONDecodeError:
|
2014-04-17 17:44:30 +08:00
|
|
|
self.fail("Second argument is not valid JSON: %r" % expected_data)
|
|
|
|
self.assertNotEqual(data, expected_data, msg=msg)
|
|
|
|
|
2013-05-19 06:04:34 +08:00
|
|
|
def assertXMLEqual(self, xml1, xml2, msg=None):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that two XML snippets are semantically the same.
|
|
|
|
Whitespace in most cases is ignored and attribute ordering is not
|
|
|
|
significant. The arguments must be valid XML.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
result = compare_xml(xml1, xml2)
|
|
|
|
except Exception as e:
|
|
|
|
standardMsg = 'First or second argument is not valid XML\n%s' % e
|
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
else:
|
|
|
|
if not result:
|
|
|
|
standardMsg = '%s != %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
|
2015-08-03 04:07:31 +08:00
|
|
|
diff = ('\n' + '\n'.join(
|
2016-12-29 23:27:49 +08:00
|
|
|
difflib.ndiff(xml1.splitlines(), xml2.splitlines())
|
2015-08-03 04:07:31 +08:00
|
|
|
))
|
|
|
|
standardMsg = self._truncateMessage(standardMsg, diff)
|
2013-05-19 06:04:34 +08:00
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
|
|
|
|
def assertXMLNotEqual(self, xml1, xml2, msg=None):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Assert that two XML snippets are not semantically equivalent.
|
|
|
|
Whitespace in most cases is ignored and attribute ordering is not
|
|
|
|
significant. The arguments must be valid XML.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
|
|
|
try:
|
|
|
|
result = compare_xml(xml1, xml2)
|
|
|
|
except Exception as e:
|
|
|
|
standardMsg = 'First or second argument is not valid XML\n%s' % e
|
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
else:
|
|
|
|
if result:
|
|
|
|
standardMsg = '%s == %s' % (safe_repr(xml1, True), safe_repr(xml2, True))
|
|
|
|
self.fail(self._formatMessage(msg, standardMsg))
|
|
|
|
|
|
|
|
|
|
|
|
class TransactionTestCase(SimpleTestCase):
|
|
|
|
|
|
|
|
# Subclasses can ask for resetting of auto increment sequence before each
|
|
|
|
# test case
|
|
|
|
reset_sequences = False
|
|
|
|
|
2013-06-04 14:13:36 +08:00
|
|
|
# Subclasses can enable only a subset of apps for faster tests
|
|
|
|
available_apps = None
|
|
|
|
|
2013-09-11 21:20:15 +08:00
|
|
|
# Subclasses can define fixtures which will be automatically installed.
|
|
|
|
fixtures = None
|
|
|
|
|
2019-09-07 17:57:46 +08:00
|
|
|
databases = {DEFAULT_DB_ALIAS}
|
2018-07-12 12:12:20 +08:00
|
|
|
_disallowed_database_msg = (
|
2019-01-13 03:33:50 +08:00
|
|
|
'Database %(operation)s to %(alias)r are not allowed in this test. '
|
|
|
|
'Add %(alias)r to %(test)s.databases to ensure proper test isolation '
|
2018-07-12 12:12:20 +08:00
|
|
|
'and silence this failure.'
|
|
|
|
)
|
2017-02-13 21:46:00 +08:00
|
|
|
|
2014-06-09 10:30:15 +08:00
|
|
|
# If transactions aren't available, Django will serialize the database
|
|
|
|
# contents into a fixture during setup and flush and reload them
|
|
|
|
# during teardown (as flush does not restore data from migrations).
|
|
|
|
# This can be slow; this flag allows enabling on a per-case basis.
|
|
|
|
serialized_rollback = False
|
|
|
|
|
2013-05-19 06:04:34 +08:00
|
|
|
def _pre_setup(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
Perform pre-test setup:
|
|
|
|
* If the class has an 'available_apps' attribute, restrict the app
|
|
|
|
registry to these applications, then fire the post_migrate signal --
|
|
|
|
it must run with the correct set of applications for the test case.
|
|
|
|
* If the class has a 'fixtures' attribute, install those fixtures.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
super()._pre_setup()
|
2013-06-04 14:13:36 +08:00
|
|
|
if self.available_apps is not None:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.set_available_apps(self.available_apps)
|
2016-03-29 06:33:29 +08:00
|
|
|
setting_changed.send(
|
|
|
|
sender=settings._wrapped.__class__,
|
|
|
|
setting='INSTALLED_APPS',
|
|
|
|
value=self.available_apps,
|
|
|
|
enter=True,
|
|
|
|
)
|
2013-06-12 04:56:09 +08:00
|
|
|
for db_name in self._databases_names(include_mirrors=False):
|
2015-02-28 23:02:20 +08:00
|
|
|
emit_post_migrate_signal(verbosity=0, interactive=False, db=db_name)
|
2013-06-04 14:13:36 +08:00
|
|
|
try:
|
|
|
|
self._fixture_setup()
|
|
|
|
except Exception:
|
|
|
|
if self.available_apps is not None:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.unset_available_apps()
|
2016-03-29 06:33:29 +08:00
|
|
|
setting_changed.send(
|
|
|
|
sender=settings._wrapped.__class__,
|
|
|
|
setting='INSTALLED_APPS',
|
|
|
|
value=settings.INSTALLED_APPS,
|
|
|
|
enter=False,
|
|
|
|
)
|
2013-06-04 14:13:36 +08:00
|
|
|
raise
|
2017-06-19 09:24:20 +08:00
|
|
|
# Clear the queries_log so that it's less likely to overflow (a single
|
2017-02-28 09:00:09 +08:00
|
|
|
# test probably won't execute 9K queries). If queries_log overflows,
|
|
|
|
# then assertNumQueries() doesn't work.
|
|
|
|
for db_name in self._databases_names(include_mirrors=False):
|
|
|
|
connections[db_name].queries_log.clear()
|
2013-05-19 06:04:34 +08:00
|
|
|
|
2014-10-19 05:01:13 +08:00
|
|
|
@classmethod
|
|
|
|
def _databases_names(cls, include_mirrors=True):
|
2018-07-12 12:12:20 +08:00
|
|
|
# Only consider allowed database aliases, including mirrors or not.
|
|
|
|
return [
|
|
|
|
alias for alias in connections
|
|
|
|
if alias in cls.databases and (
|
|
|
|
include_mirrors or not connections[alias].settings_dict['TEST']['MIRROR']
|
|
|
|
)
|
|
|
|
]
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def _reset_sequences(self, db_name):
|
|
|
|
conn = connections[db_name]
|
|
|
|
if conn.features.supports_sequence_reset:
|
2013-09-22 20:01:57 +08:00
|
|
|
sql_list = conn.ops.sequence_reset_by_name_sql(
|
2013-10-20 07:33:10 +08:00
|
|
|
no_style(), conn.introspection.sequence_list())
|
2013-05-19 06:04:34 +08:00
|
|
|
if sql_list:
|
2014-03-21 21:21:43 +08:00
|
|
|
with transaction.atomic(using=db_name):
|
2017-11-28 21:12:28 +08:00
|
|
|
with conn.cursor() as cursor:
|
|
|
|
for sql in sql_list:
|
|
|
|
cursor.execute(sql)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def _fixture_setup(self):
|
|
|
|
for db_name in self._databases_names(include_mirrors=False):
|
|
|
|
# Reset sequences
|
|
|
|
if self.reset_sequences:
|
|
|
|
self._reset_sequences(db_name)
|
|
|
|
|
2018-12-06 04:21:09 +08:00
|
|
|
# Provide replica initial data from migrated apps, if needed.
|
|
|
|
if self.serialized_rollback and hasattr(connections[db_name], "_test_serialized_contents"):
|
|
|
|
if self.available_apps is not None:
|
|
|
|
apps.unset_available_apps()
|
|
|
|
connections[db_name].creation.deserialize_db_from_string(
|
|
|
|
connections[db_name]._test_serialized_contents
|
|
|
|
)
|
|
|
|
if self.available_apps is not None:
|
|
|
|
apps.set_available_apps(self.available_apps)
|
|
|
|
|
2013-09-11 21:20:15 +08:00
|
|
|
if self.fixtures:
|
2013-05-19 06:04:34 +08:00
|
|
|
# We have to use this slightly awkward syntax due to the fact
|
|
|
|
# that we're using *args and **kwargs together.
|
|
|
|
call_command('loaddata', *self.fixtures,
|
2014-10-20 03:25:09 +08:00
|
|
|
**{'verbosity': 0, 'database': db_name})
|
2013-05-19 06:04:34 +08:00
|
|
|
|
2014-10-19 05:01:13 +08:00
|
|
|
def _should_reload_connections(self):
|
|
|
|
return True
|
|
|
|
|
2013-05-19 06:04:34 +08:00
|
|
|
def _post_teardown(self):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""
|
|
|
|
Perform post-test things:
|
|
|
|
* Flush the contents of the database to leave a clean slate. If the
|
|
|
|
class has an 'available_apps' attribute, don't fire post_migrate.
|
|
|
|
* Force-close the connection so the next test gets a clean cursor.
|
2013-05-19 06:04:34 +08:00
|
|
|
"""
|
2013-06-04 14:13:36 +08:00
|
|
|
try:
|
|
|
|
self._fixture_teardown()
|
2017-01-21 21:13:44 +08:00
|
|
|
super()._post_teardown()
|
2014-10-19 05:01:13 +08:00
|
|
|
if self._should_reload_connections():
|
|
|
|
# Some DB cursors include SQL statements as part of cursor
|
|
|
|
# creation. If you have a test that does a rollback, the effect
|
|
|
|
# of these statements is lost, which can affect the operation of
|
|
|
|
# tests (e.g., losing a timezone setting causing objects to be
|
|
|
|
# created with the wrong time). To make sure this doesn't
|
|
|
|
# happen, get a clean connection at the start of every test.
|
|
|
|
for conn in connections.all():
|
|
|
|
conn.close()
|
2013-06-04 14:13:36 +08:00
|
|
|
finally:
|
2013-12-23 07:10:53 +08:00
|
|
|
if self.available_apps is not None:
|
2013-12-24 19:25:17 +08:00
|
|
|
apps.unset_available_apps()
|
2013-12-23 07:10:53 +08:00
|
|
|
setting_changed.send(sender=settings._wrapped.__class__,
|
|
|
|
setting='INSTALLED_APPS',
|
|
|
|
value=settings.INSTALLED_APPS,
|
|
|
|
enter=False)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
|
|
|
def _fixture_teardown(self):
|
2013-07-30 18:52:52 +08:00
|
|
|
# Allow TRUNCATE ... CASCADE and don't emit the post_migrate signal
|
2013-06-12 04:56:09 +08:00
|
|
|
# when flushing only a subset of the apps
|
2013-05-19 06:04:34 +08:00
|
|
|
for db_name in self._databases_names(include_mirrors=False):
|
2014-06-09 10:30:15 +08:00
|
|
|
# Flush the database
|
2015-04-14 22:43:57 +08:00
|
|
|
inhibit_post_migrate = (
|
2016-04-04 08:37:32 +08:00
|
|
|
self.available_apps is not None or
|
|
|
|
( # Inhibit the post_migrate signal when using serialized
|
2015-04-14 22:43:57 +08:00
|
|
|
# rollback to avoid trying to recreate the serialized data.
|
|
|
|
self.serialized_rollback and
|
|
|
|
hasattr(connections[db_name], '_test_serialized_contents')
|
|
|
|
)
|
|
|
|
)
|
2013-06-04 14:13:36 +08:00
|
|
|
call_command('flush', verbosity=0, interactive=False,
|
2014-10-20 03:25:09 +08:00
|
|
|
database=db_name, reset_sequences=False,
|
2013-06-12 04:56:09 +08:00
|
|
|
allow_cascade=self.available_apps is not None,
|
2015-04-14 22:43:57 +08:00
|
|
|
inhibit_post_migrate=inhibit_post_migrate)
|
2013-05-19 06:04:34 +08:00
|
|
|
|
2014-02-10 18:18:20 +08:00
|
|
|
def assertQuerysetEqual(self, qs, values, transform=repr, ordered=True, msg=None):
|
2017-01-07 19:11:46 +08:00
|
|
|
items = map(transform, qs)
|
2011-08-23 11:38:18 +08:00
|
|
|
if not ordered:
|
2014-09-29 23:17:44 +08:00
|
|
|
return self.assertEqual(Counter(items), Counter(values), msg=msg)
|
2012-12-13 19:33:11 +08:00
|
|
|
values = list(values)
|
|
|
|
# For example qs.iterator() could be passed as qs, but it does not
|
|
|
|
# have 'ordered' attribute.
|
|
|
|
if len(values) > 1 and hasattr(qs, 'ordered') and not qs.ordered:
|
|
|
|
raise ValueError("Trying to compare non-ordered queryset "
|
|
|
|
"against more than one ordered values")
|
2014-02-10 18:18:20 +08:00
|
|
|
return self.assertEqual(list(items), values, msg=msg)
|
2010-05-28 19:15:36 +08:00
|
|
|
|
2017-02-02 00:41:56 +08:00
|
|
|
def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs):
|
2011-08-23 10:32:37 +08:00
|
|
|
conn = connections[using]
|
2010-10-12 11:33:19 +08:00
|
|
|
|
2011-08-23 10:32:37 +08:00
|
|
|
context = _AssertNumQueriesContext(self, num, conn)
|
2010-10-12 11:33:19 +08:00
|
|
|
if func is None:
|
|
|
|
return context
|
|
|
|
|
2011-03-28 13:58:43 +08:00
|
|
|
with context:
|
2010-10-12 11:33:19 +08:00
|
|
|
func(*args, **kwargs)
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2018-07-12 12:12:20 +08:00
|
|
|
def connections_support_transactions(aliases=None):
|
|
|
|
"""
|
|
|
|
Return whether or not all (or specified) connections support
|
|
|
|
transactions.
|
|
|
|
"""
|
|
|
|
conns = connections.all() if aliases is None else (connections[alias] for alias in aliases)
|
|
|
|
return all(conn.features.supports_transactions for conn in conns)
|
|
|
|
|
|
|
|
|
2009-01-16 10:30:22 +08:00
|
|
|
class TestCase(TransactionTestCase):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Similar to TransactionTestCase, but use `transaction.atomic()` to achieve
|
2014-10-19 05:01:13 +08:00
|
|
|
test isolation.
|
|
|
|
|
2015-11-03 17:55:10 +08:00
|
|
|
In most situations, TestCase should be preferred to TransactionTestCase as
|
2014-10-19 05:01:13 +08:00
|
|
|
it allows faster execution. However, there are some situations where using
|
|
|
|
TransactionTestCase might be necessary (e.g. testing some transactional
|
|
|
|
behavior).
|
|
|
|
|
|
|
|
On database backends with no transaction support, TestCase behaves as
|
|
|
|
TransactionTestCase.
|
2009-01-16 10:30:22 +08:00
|
|
|
"""
|
2014-12-04 21:05:59 +08:00
|
|
|
@classmethod
|
|
|
|
def _enter_atomics(cls):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Open atomic blocks for multiple databases."""
|
2014-12-04 21:05:59 +08:00
|
|
|
atomics = {}
|
|
|
|
for db_name in cls._databases_names():
|
|
|
|
atomics[db_name] = transaction.atomic(using=db_name)
|
|
|
|
atomics[db_name].__enter__()
|
|
|
|
return atomics
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def _rollback_atomics(cls, atomics):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Rollback atomic blocks opened by the previous method."""
|
2014-12-04 21:05:59 +08:00
|
|
|
for db_name in reversed(cls._databases_names()):
|
|
|
|
transaction.set_rollback(True, using=db_name)
|
|
|
|
atomics[db_name].__exit__(None, None, None)
|
2009-01-16 10:30:22 +08:00
|
|
|
|
2018-07-12 12:12:20 +08:00
|
|
|
@classmethod
|
|
|
|
def _databases_support_transactions(cls):
|
|
|
|
return connections_support_transactions(cls.databases)
|
|
|
|
|
2014-10-19 05:01:13 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUpClass()
|
2018-07-12 12:12:20 +08:00
|
|
|
if not cls._databases_support_transactions():
|
2014-10-19 05:01:13 +08:00
|
|
|
return
|
2014-12-04 21:05:59 +08:00
|
|
|
cls.cls_atomics = cls._enter_atomics()
|
|
|
|
|
|
|
|
if cls.fixtures:
|
|
|
|
for db_name in cls._databases_names(include_mirrors=False):
|
2017-06-16 20:47:17 +08:00
|
|
|
try:
|
|
|
|
call_command('loaddata', *cls.fixtures, **{'verbosity': 0, 'database': db_name})
|
|
|
|
except Exception:
|
|
|
|
cls._rollback_atomics(cls.cls_atomics)
|
2019-01-13 03:33:50 +08:00
|
|
|
cls._remove_databases_failures()
|
2017-06-16 20:47:17 +08:00
|
|
|
raise
|
2015-07-27 00:42:21 +08:00
|
|
|
try:
|
|
|
|
cls.setUpTestData()
|
|
|
|
except Exception:
|
|
|
|
cls._rollback_atomics(cls.cls_atomics)
|
2019-01-13 03:33:50 +08:00
|
|
|
cls._remove_databases_failures()
|
2015-07-27 00:42:21 +08:00
|
|
|
raise
|
2014-10-19 05:01:13 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2018-07-12 12:12:20 +08:00
|
|
|
if cls._databases_support_transactions():
|
2014-12-04 21:05:59 +08:00
|
|
|
cls._rollback_atomics(cls.cls_atomics)
|
2014-10-19 05:01:13 +08:00
|
|
|
for conn in connections.all():
|
|
|
|
conn.close()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDownClass()
|
2014-10-19 05:01:13 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def setUpTestData(cls):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Load initial data for the TestCase."""
|
2014-10-19 05:01:13 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
def _should_reload_connections(self):
|
2018-07-12 12:12:20 +08:00
|
|
|
if self._databases_support_transactions():
|
2014-10-19 05:01:13 +08:00
|
|
|
return False
|
2017-01-21 21:13:44 +08:00
|
|
|
return super()._should_reload_connections()
|
2014-10-19 05:01:13 +08:00
|
|
|
|
2009-01-16 10:30:22 +08:00
|
|
|
def _fixture_setup(self):
|
2018-07-12 12:12:20 +08:00
|
|
|
if not self._databases_support_transactions():
|
2014-10-19 05:01:13 +08:00
|
|
|
# If the backend does not support transactions, we should reload
|
|
|
|
# class data before each test
|
|
|
|
self.setUpTestData()
|
2017-01-21 21:13:44 +08:00
|
|
|
return super()._fixture_setup()
|
2009-02-27 21:14:59 +08:00
|
|
|
|
2012-07-25 04:24:16 +08:00
|
|
|
assert not self.reset_sequences, 'reset_sequences cannot be used on TestCase instances'
|
2014-12-04 21:05:59 +08:00
|
|
|
self.atomics = self._enter_atomics()
|
2009-01-16 10:30:22 +08:00
|
|
|
|
|
|
|
def _fixture_teardown(self):
|
2018-07-12 12:12:20 +08:00
|
|
|
if not self._databases_support_transactions():
|
2017-01-21 21:13:44 +08:00
|
|
|
return super()._fixture_teardown()
|
2016-02-13 08:41:31 +08:00
|
|
|
try:
|
|
|
|
for db_name in reversed(self._databases_names()):
|
|
|
|
if self._should_check_constraints(connections[db_name]):
|
|
|
|
connections[db_name].check_constraints()
|
|
|
|
finally:
|
|
|
|
self._rollback_atomics(self.atomics)
|
|
|
|
|
|
|
|
def _should_check_constraints(self, connection):
|
|
|
|
return (
|
|
|
|
connection.features.can_defer_constraint_checks and
|
|
|
|
not connection.needs_rollback and connection.is_usable()
|
|
|
|
)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class CheckCondition:
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Descriptor class for deferred condition checking."""
|
2016-09-13 10:06:31 +08:00
|
|
|
def __init__(self, *conditions):
|
|
|
|
self.conditions = conditions
|
|
|
|
|
|
|
|
def add_condition(self, condition, reason):
|
2017-12-22 10:05:23 +08:00
|
|
|
return self.__class__(*self.conditions, (condition, reason))
|
2013-07-20 02:30:14 +08:00
|
|
|
|
2015-10-26 23:31:16 +08:00
|
|
|
def __get__(self, instance, cls=None):
|
2016-09-13 10:06:31 +08:00
|
|
|
# Trigger access for all bases.
|
|
|
|
if any(getattr(base, '__unittest_skip__', False) for base in cls.__bases__):
|
|
|
|
return True
|
|
|
|
for condition, reason in self.conditions:
|
|
|
|
if condition():
|
|
|
|
# Override this descriptor's value and set the skip reason.
|
|
|
|
cls.__unittest_skip__ = True
|
|
|
|
cls.__unittest_skip_why__ = reason
|
|
|
|
return True
|
|
|
|
return False
|
2013-07-20 02:30:14 +08:00
|
|
|
|
|
|
|
|
2019-01-13 05:14:54 +08:00
|
|
|
def _deferredSkip(condition, reason, name):
|
2010-10-17 12:26:47 +08:00
|
|
|
def decorator(test_func):
|
2019-01-13 05:14:54 +08:00
|
|
|
nonlocal condition
|
2011-10-05 20:50:44 +08:00
|
|
|
if not (isinstance(test_func, type) and
|
2013-07-20 02:30:14 +08:00
|
|
|
issubclass(test_func, unittest.TestCase)):
|
2010-10-17 12:26:47 +08:00
|
|
|
@wraps(test_func)
|
2010-10-11 20:55:17 +08:00
|
|
|
def skip_wrapper(*args, **kwargs):
|
2019-01-13 05:14:54 +08:00
|
|
|
if (args and isinstance(args[0], unittest.TestCase) and
|
|
|
|
connection.alias not in getattr(args[0], 'databases', {})):
|
|
|
|
raise ValueError(
|
|
|
|
"%s cannot be used on %s as %s doesn't allow queries "
|
|
|
|
"against the %r database." % (
|
|
|
|
name,
|
|
|
|
args[0],
|
|
|
|
args[0].__class__.__qualname__,
|
|
|
|
connection.alias,
|
|
|
|
)
|
|
|
|
)
|
2010-10-11 20:55:17 +08:00
|
|
|
if condition():
|
2013-07-01 20:22:27 +08:00
|
|
|
raise unittest.SkipTest(reason)
|
2010-10-17 12:26:47 +08:00
|
|
|
return test_func(*args, **kwargs)
|
2010-10-11 20:55:17 +08:00
|
|
|
test_item = skip_wrapper
|
2010-10-17 12:26:47 +08:00
|
|
|
else:
|
2013-07-20 02:30:14 +08:00
|
|
|
# Assume a class is decorated
|
2010-10-17 12:26:47 +08:00
|
|
|
test_item = test_func
|
2019-01-13 05:14:54 +08:00
|
|
|
databases = getattr(test_item, 'databases', None)
|
|
|
|
if not databases or connection.alias not in databases:
|
|
|
|
# Defer raising to allow importing test class's module.
|
|
|
|
def condition():
|
|
|
|
raise ValueError(
|
|
|
|
"%s cannot be used on %s as it doesn't allow queries "
|
|
|
|
"against the '%s' database." % (
|
|
|
|
name, test_item, connection.alias,
|
|
|
|
)
|
|
|
|
)
|
2016-09-13 10:06:31 +08:00
|
|
|
# Retrieve the possibly existing value from the class's dict to
|
|
|
|
# avoid triggering the descriptor.
|
|
|
|
skip = test_func.__dict__.get('__unittest_skip__')
|
|
|
|
if isinstance(skip, CheckCondition):
|
|
|
|
test_item.__unittest_skip__ = skip.add_condition(condition, reason)
|
|
|
|
elif skip is not True:
|
|
|
|
test_item.__unittest_skip__ = CheckCondition((condition, reason))
|
2010-10-11 20:55:17 +08:00
|
|
|
return test_item
|
|
|
|
return decorator
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2014-08-24 00:01:33 +08:00
|
|
|
def skipIfDBFeature(*features):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Skip a test if a database has at least one of the named features."""
|
2014-08-24 00:01:33 +08:00
|
|
|
return _deferredSkip(
|
|
|
|
lambda: any(getattr(connection.features, feature, False) for feature in features),
|
2019-01-13 05:14:54 +08:00
|
|
|
"Database has feature(s) %s" % ", ".join(features),
|
|
|
|
'skipIfDBFeature',
|
2014-08-24 00:01:33 +08:00
|
|
|
)
|
2010-10-11 20:55:17 +08:00
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2014-08-24 00:01:33 +08:00
|
|
|
def skipUnlessDBFeature(*features):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Skip a test unless a database has all the named features."""
|
2014-08-24 00:01:33 +08:00
|
|
|
return _deferredSkip(
|
|
|
|
lambda: not all(getattr(connection.features, feature, False) for feature in features),
|
2019-01-13 05:14:54 +08:00
|
|
|
"Database doesn't support feature(s): %s" % ", ".join(features),
|
|
|
|
'skipUnlessDBFeature',
|
2014-08-24 00:01:33 +08:00
|
|
|
)
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
|
|
|
|
2015-03-27 04:54:43 +08:00
|
|
|
def skipUnlessAnyDBFeature(*features):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Skip a test unless a database has any of the named features."""
|
2015-03-27 04:54:43 +08:00
|
|
|
return _deferredSkip(
|
|
|
|
lambda: not any(getattr(connection.features, feature, False) for feature in features),
|
2019-01-13 05:14:54 +08:00
|
|
|
"Database doesn't support any of the feature(s): %s" % ", ".join(features),
|
|
|
|
'skipUnlessAnyDBFeature',
|
2015-03-27 04:54:43 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
class QuietWSGIRequestHandler(WSGIRequestHandler):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
A WSGIRequestHandler that doesn't log to standard output any of the
|
|
|
|
requests received, so as to not clutter the test result output.
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
"""
|
|
|
|
def log_message(*args):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2013-06-02 01:24:46 +08:00
|
|
|
class FSFilesHandler(WSGIHandler):
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
"""
|
2013-06-02 01:24:46 +08:00
|
|
|
WSGI middleware that intercepts calls to a directory, as defined by one of
|
|
|
|
the *_ROOT settings, and serves those files, publishing them under *_URL.
|
|
|
|
"""
|
|
|
|
def __init__(self, application):
|
|
|
|
self.application = application
|
|
|
|
self.base_url = urlparse(self.get_base_url())
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
2013-06-02 01:24:46 +08:00
|
|
|
|
|
|
|
def _should_handle(self, path):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Check if the path should be handled. Ignore the path if:
|
2013-06-02 01:24:46 +08:00
|
|
|
* the host is provided as part of the base_url
|
|
|
|
* the request's path isn't under the media path (or equal)
|
|
|
|
"""
|
|
|
|
return path.startswith(self.base_url[2]) and not self.base_url[1]
|
|
|
|
|
|
|
|
def file_path(self, url):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Return the relative path to the file on disk for the given URL."""
|
2013-06-02 01:24:46 +08:00
|
|
|
relative_url = url[len(self.base_url[2]):]
|
|
|
|
return url2pathname(relative_url)
|
|
|
|
|
|
|
|
def get_response(self, request):
|
|
|
|
from django.http import Http404
|
|
|
|
|
|
|
|
if self._should_handle(request.path):
|
|
|
|
try:
|
|
|
|
return self.serve(request)
|
|
|
|
except Http404:
|
|
|
|
pass
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().get_response(request)
|
2013-06-02 01:24:46 +08:00
|
|
|
|
|
|
|
def serve(self, request):
|
|
|
|
os_rel_path = self.file_path(request.path)
|
2013-09-28 08:45:25 +08:00
|
|
|
os_rel_path = posixpath.normpath(unquote(os_rel_path))
|
|
|
|
# Emulate behavior of django.contrib.staticfiles.views.serve() when it
|
|
|
|
# invokes staticfiles' finders functionality.
|
|
|
|
# TODO: Modify if/when that internal API is refactored
|
|
|
|
final_rel_path = os_rel_path.replace('\\', '/').lstrip('/')
|
2013-06-02 01:24:46 +08:00
|
|
|
return serve(request, final_rel_path, document_root=self.get_base_dir())
|
|
|
|
|
|
|
|
def __call__(self, environ, start_response):
|
|
|
|
if not self._should_handle(get_path_info(environ)):
|
|
|
|
return self.application(environ, start_response)
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().__call__(environ, start_response)
|
2013-06-02 01:24:46 +08:00
|
|
|
|
|
|
|
|
|
|
|
class _StaticFilesHandler(FSFilesHandler):
|
|
|
|
"""
|
|
|
|
Handler for serving static files. A private class that is meant to be used
|
|
|
|
solely as a convenience by LiveServerThread.
|
|
|
|
"""
|
|
|
|
def get_base_dir(self):
|
|
|
|
return settings.STATIC_ROOT
|
|
|
|
|
|
|
|
def get_base_url(self):
|
|
|
|
return settings.STATIC_URL
|
|
|
|
|
|
|
|
|
|
|
|
class _MediaFilesHandler(FSFilesHandler):
|
|
|
|
"""
|
|
|
|
Handler for serving the media files. A private class that is meant to be
|
|
|
|
used solely as a convenience by LiveServerThread.
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
"""
|
|
|
|
def get_base_dir(self):
|
|
|
|
return settings.MEDIA_ROOT
|
|
|
|
|
|
|
|
def get_base_url(self):
|
|
|
|
return settings.MEDIA_URL
|
|
|
|
|
|
|
|
|
|
|
|
class LiveServerThread(threading.Thread):
|
2017-01-25 04:37:33 +08:00
|
|
|
"""Thread for running a live http server while the tests are running."""
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2017-05-23 01:16:56 +08:00
|
|
|
def __init__(self, host, static_handler, connections_override=None, port=0):
|
2011-12-30 04:22:13 +08:00
|
|
|
self.host = host
|
2017-05-23 01:16:56 +08:00
|
|
|
self.port = port
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
self.is_ready = threading.Event()
|
|
|
|
self.error = None
|
2013-06-02 01:24:46 +08:00
|
|
|
self.static_handler = static_handler
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
self.connections_override = connections_override
|
2017-01-21 21:13:44 +08:00
|
|
|
super().__init__()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
|
|
|
def run(self):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Set up the live server and databases, and then loop over handling
|
|
|
|
HTTP requests.
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
"""
|
|
|
|
if self.connections_override:
|
|
|
|
# Override this thread's database connections with the ones
|
|
|
|
# provided by the main thread.
|
|
|
|
for alias, conn in self.connections_override.items():
|
|
|
|
connections[alias] = conn
|
|
|
|
try:
|
|
|
|
# Create the handler for serving static and media files
|
2013-06-02 01:24:46 +08:00
|
|
|
handler = self.static_handler(_MediaFilesHandler(WSGIHandler()))
|
2017-05-23 01:16:56 +08:00
|
|
|
self.httpd = self._create_server()
|
|
|
|
# If binding to port zero, assign the port allocated by the OS.
|
|
|
|
if self.port == 0:
|
|
|
|
self.port = self.httpd.server_address[1]
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
self.httpd.set_app(handler)
|
|
|
|
self.is_ready.set()
|
|
|
|
self.httpd.serve_forever()
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as e:
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
self.error = e
|
|
|
|
self.is_ready.set()
|
2016-08-20 00:47:41 +08:00
|
|
|
finally:
|
|
|
|
connections.close_all()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2017-05-23 01:16:56 +08:00
|
|
|
def _create_server(self):
|
|
|
|
return ThreadedWSGIServer((self.host, self.port), QuietWSGIRequestHandler, allow_reuse_address=False)
|
2015-08-30 20:27:38 +08:00
|
|
|
|
2013-10-02 21:27:38 +08:00
|
|
|
def terminate(self):
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
if hasattr(self, 'httpd'):
|
|
|
|
# Stop the WSGI server
|
|
|
|
self.httpd.shutdown()
|
|
|
|
self.httpd.server_close()
|
2016-08-20 00:47:41 +08:00
|
|
|
self.join()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
|
|
|
|
|
|
|
class LiveServerTestCase(TransactionTestCase):
|
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Do basically the same as TransactionTestCase but also launch a live HTTP
|
|
|
|
server in a separate thread so that the tests may use another testing
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
framework, such as Selenium for example, instead of the built-in dummy
|
|
|
|
client.
|
2017-01-25 04:37:33 +08:00
|
|
|
It inherits from TransactionTestCase instead of TestCase because the
|
|
|
|
threads don't share the same transactions (unless if using in-memory sqlite)
|
|
|
|
and each thread needs to commit all their transactions so that the other
|
|
|
|
thread can see the changes.
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
"""
|
2016-06-24 00:04:05 +08:00
|
|
|
host = 'localhost'
|
2017-05-23 01:16:56 +08:00
|
|
|
port = 0
|
2016-08-02 04:15:41 +08:00
|
|
|
server_thread_class = LiveServerThread
|
2013-06-02 01:24:46 +08:00
|
|
|
static_handler = _StaticFilesHandler
|
|
|
|
|
2015-06-11 04:57:51 +08:00
|
|
|
@classproperty
|
|
|
|
def live_server_url(cls):
|
2016-06-24 00:04:05 +08:00
|
|
|
return 'http://%s:%s' % (cls.host, cls.server_thread.port)
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
|
2018-10-26 01:52:29 +08:00
|
|
|
@classproperty
|
|
|
|
def allowed_host(cls):
|
|
|
|
return cls.host
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUpClass()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
connections_override = {}
|
|
|
|
for conn in connections.all():
|
|
|
|
# If using in-memory sqlite databases, pass the connections to
|
|
|
|
# the server thread.
|
2016-08-18 08:34:18 +08:00
|
|
|
if conn.vendor == 'sqlite' and conn.is_in_memory_db():
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
# Explicitly enable thread-shareability for this connection
|
2019-02-14 23:04:55 +08:00
|
|
|
conn.inc_thread_sharing()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
connections_override[conn.alias] = conn
|
|
|
|
|
2016-06-04 06:02:38 +08:00
|
|
|
cls._live_server_modified_settings = modify_settings(
|
2018-10-26 01:52:29 +08:00
|
|
|
ALLOWED_HOSTS={'append': cls.allowed_host},
|
2016-06-04 06:02:38 +08:00
|
|
|
)
|
|
|
|
cls._live_server_modified_settings.enable()
|
2016-06-24 00:04:05 +08:00
|
|
|
cls.server_thread = cls._create_server_thread(connections_override)
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
cls.server_thread.daemon = True
|
|
|
|
cls.server_thread.start()
|
|
|
|
|
|
|
|
# Wait for the live server to be ready
|
|
|
|
cls.server_thread.is_ready.wait()
|
|
|
|
if cls.server_thread.error:
|
Final attempt to solve sporadic test failures.
tearDownClass is not called if setUpClass throws an exception, in our case
this means that LiveServerTestCase leaks LiveServerThread sockets if the
test happens to be skipped later on, and AdminSeleniumWebDriverTestCase
doesn't close it's already open browser window. To prevent this leakage
we catch errors where needed and manually call _tearDownClassInternal.
_tearDownClassInternal should be written as defensively as possible since
it is not allowed to make any assumptions on how far setUpClass got.
This patch should fix the sporadic "Address already in use"-errors on jenkins
and also the "This code isn't under transaction management"-error for sqlite
(also just on jenkins).
After discussion with koniiiik, jezdez, kmtracey, tos9, lifeless, nedbat and
voidspace it was decided that this is the safest approach (thanks to everyone
for their comments and help). Manually calling tearDownClass was shut down
cause we don't know how our users override our classes.
This is a private and very specialized API on purpose and should not be used
without a strong reason!
This patch partially reverts the earlier attempts to fix those issues,
namely:
2fa0dd73b18f55d0fdd1c1d54b1d18031bfcf1ed and
3c5775d36f7e431d9691829a78580873111cb714
Final note: If this patch breaks in a later version of Django, please be
very careful on how you fix it, you might not see test failures locally.
That said, this patch hopefully doesn't produce even more failures.
2013-09-17 22:28:20 +08:00
|
|
|
# Clean up behind ourselves, since tearDownClass won't get called in
|
|
|
|
# case of errors.
|
|
|
|
cls._tearDownClassInternal()
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
raise cls.server_thread.error
|
|
|
|
|
2015-08-30 20:27:38 +08:00
|
|
|
@classmethod
|
2016-06-24 00:04:05 +08:00
|
|
|
def _create_server_thread(cls, connections_override):
|
2016-08-02 04:15:41 +08:00
|
|
|
return cls.server_thread_class(
|
2016-06-24 00:04:05 +08:00
|
|
|
cls.host,
|
2015-08-30 20:27:38 +08:00
|
|
|
cls.static_handler,
|
|
|
|
connections_override=connections_override,
|
2017-05-23 01:16:56 +08:00
|
|
|
port=cls.port,
|
2015-08-30 20:27:38 +08:00
|
|
|
)
|
|
|
|
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
@classmethod
|
Final attempt to solve sporadic test failures.
tearDownClass is not called if setUpClass throws an exception, in our case
this means that LiveServerTestCase leaks LiveServerThread sockets if the
test happens to be skipped later on, and AdminSeleniumWebDriverTestCase
doesn't close it's already open browser window. To prevent this leakage
we catch errors where needed and manually call _tearDownClassInternal.
_tearDownClassInternal should be written as defensively as possible since
it is not allowed to make any assumptions on how far setUpClass got.
This patch should fix the sporadic "Address already in use"-errors on jenkins
and also the "This code isn't under transaction management"-error for sqlite
(also just on jenkins).
After discussion with koniiiik, jezdez, kmtracey, tos9, lifeless, nedbat and
voidspace it was decided that this is the safest approach (thanks to everyone
for their comments and help). Manually calling tearDownClass was shut down
cause we don't know how our users override our classes.
This is a private and very specialized API on purpose and should not be used
without a strong reason!
This patch partially reverts the earlier attempts to fix those issues,
namely:
2fa0dd73b18f55d0fdd1c1d54b1d18031bfcf1ed and
3c5775d36f7e431d9691829a78580873111cb714
Final note: If this patch breaks in a later version of Django, please be
very careful on how you fix it, you might not see test failures locally.
That said, this patch hopefully doesn't produce even more failures.
2013-09-17 22:28:20 +08:00
|
|
|
def _tearDownClassInternal(cls):
|
Fixed #2879 -- Added support for the integration with Selenium and other in-browser testing frameworks. Also added the first Selenium tests for `contrib.admin`. Many thanks to everyone for their contributions and feedback: Mikeal Rogers, Dirk Datzert, mir, Simon G., Almad, Russell Keith-Magee, Denis Golomazov, devin, robertrv, andrewbadr, Idan Gazit, voidspace, Tom Christie, hjwp2, Adam Nelson, Jannis Leidel, Anssi Kääriäinen, Preston Holmes, Bruno Renié and Jacob Kaplan-Moss.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@17241 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2011-12-22 16:33:58 +08:00
|
|
|
# There may not be a 'server_thread' attribute if setUpClass() for some
|
|
|
|
# reasons has raised an exception.
|
|
|
|
if hasattr(cls, 'server_thread'):
|
|
|
|
# Terminate the live server's thread
|
2013-10-02 21:27:38 +08:00
|
|
|
cls.server_thread.terminate()
|
2012-07-22 07:16:47 +08:00
|
|
|
|
2019-02-14 23:04:55 +08:00
|
|
|
# Restore sqlite in-memory database connections' non-shareability.
|
|
|
|
for conn in cls.server_thread.connections_override.values():
|
|
|
|
conn.dec_thread_sharing()
|
2012-07-22 07:16:47 +08:00
|
|
|
|
Final attempt to solve sporadic test failures.
tearDownClass is not called if setUpClass throws an exception, in our case
this means that LiveServerTestCase leaks LiveServerThread sockets if the
test happens to be skipped later on, and AdminSeleniumWebDriverTestCase
doesn't close it's already open browser window. To prevent this leakage
we catch errors where needed and manually call _tearDownClassInternal.
_tearDownClassInternal should be written as defensively as possible since
it is not allowed to make any assumptions on how far setUpClass got.
This patch should fix the sporadic "Address already in use"-errors on jenkins
and also the "This code isn't under transaction management"-error for sqlite
(also just on jenkins).
After discussion with koniiiik, jezdez, kmtracey, tos9, lifeless, nedbat and
voidspace it was decided that this is the safest approach (thanks to everyone
for their comments and help). Manually calling tearDownClass was shut down
cause we don't know how our users override our classes.
This is a private and very specialized API on purpose and should not be used
without a strong reason!
This patch partially reverts the earlier attempts to fix those issues,
namely:
2fa0dd73b18f55d0fdd1c1d54b1d18031bfcf1ed and
3c5775d36f7e431d9691829a78580873111cb714
Final note: If this patch breaks in a later version of Django, please be
very careful on how you fix it, you might not see test failures locally.
That said, this patch hopefully doesn't produce even more failures.
2013-09-17 22:28:20 +08:00
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
|
|
|
cls._tearDownClassInternal()
|
2016-06-04 06:02:38 +08:00
|
|
|
cls._live_server_modified_settings.disable()
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDownClass()
|
2015-02-06 18:38:22 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class SerializeMixin:
|
2015-02-06 18:38:22 +08:00
|
|
|
"""
|
2017-01-25 04:37:33 +08:00
|
|
|
Enforce serialization of TestCases that share a common resource.
|
2015-02-06 18:38:22 +08:00
|
|
|
|
|
|
|
Define a common 'lockfile' for each set of TestCases to serialize. This
|
|
|
|
file must exist on the filesystem.
|
|
|
|
|
2017-01-25 04:37:33 +08:00
|
|
|
Place it early in the MRO in order to isolate setUpClass()/tearDownClass().
|
2015-02-06 18:38:22 +08:00
|
|
|
"""
|
|
|
|
lockfile = None
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def setUpClass(cls):
|
|
|
|
if cls.lockfile is None:
|
|
|
|
raise ValueError(
|
|
|
|
"{}.lockfile isn't set. Set it to a unique value "
|
|
|
|
"in the base class.".format(cls.__name__))
|
|
|
|
cls._lockfile = open(cls.lockfile)
|
|
|
|
locks.lock(cls._lockfile, locks.LOCK_EX)
|
2017-01-21 21:13:44 +08:00
|
|
|
super().setUpClass()
|
2015-02-06 18:38:22 +08:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def tearDownClass(cls):
|
2017-01-21 21:13:44 +08:00
|
|
|
super().tearDownClass()
|
2015-02-06 18:38:22 +08:00
|
|
|
cls._lockfile.close()
|