def ready(self):
if django.VERSION[:2] == (1, 9):
import warnings
msg = "You are using an unsupported Django version. DJPT support" \
" might be dropped in any following release. See " \
"https://www.djangoproject.com/download/#supported-versions"
warnings.warn(msg)
from django_performance_testing.registry import \
SettingsOrDefaultBasedRegistry
from django_performance_testing import core
core.limits_registry = SettingsOrDefaultBasedRegistry()
from .test_client import integrate_into_test_client
integrate_into_test_client()
from .test_runner import integrate_into_django_test_runner
integrate_into_django_test_runner()
from .queries import setup_sending_before_clearing_queries_log_signal
setup_sending_before_clearing_queries_log_signal()
from .templates import integrate_into_django_templates
integrate_into_django_templates()
python类VERSION的实例源码
def test_db_version(self):
import django
if django.VERSION >= (1, 7):
cursor = 'django.db.backends.utils.CursorWrapper'
else:
cursor = 'django.db.backends.util.CursorWrapper'
with mock.patch(cursor) as mock_cursor:
mock_cursor.return_value.fetchone.return_value = ['1.0.0']
dbs = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'foo'
}
}
setattr(settings, 'DATABASES', dbs)
dbs = databases.check(request=None)
assert len(dbs) == 1
assert dbs[0]['version'] == '1.0.0'
def test_delete_cgroup(self):
cgroups = self.cinder_consistencygroups.list()
cgroup = self.cinder_consistencygroups.first()
cinder.volume_cgroup_list_with_vol_type_names(IsA(http.HttpRequest)).\
AndReturn(cgroups)
cinder.volume_cgroup_delete(IsA(http.HttpRequest), cgroup.id,
force=False)
if django.VERSION < (1, 9):
cinder.volume_cgroup_list_with_vol_type_names(
IsA(http.HttpRequest)).AndReturn(cgroups)
self.mox.ReplayAll()
formData = {'action': 'volume_cgroups__deletecg__%s' % cgroup.id}
res = self.client.post(VOLUME_CGROUPS_TAB_URL, formData, follow=True)
self.assertIn("Scheduled deletion of Consistency Group: cg_1",
[m.message for m in res.context['messages']])
def test_ssl_redirect_by_proxy(self):
dogs = horizon.get_dashboard("dogs")
puppies = dogs.get_panel("puppies")
url = puppies.get_absolute_url()
redirect_url = "?".join([settings.LOGIN_URL,
"next=%s" % url])
self.client.logout()
resp = self.client.get(url)
if django.VERSION >= (1, 9):
self.assertRedirects(resp, settings.TESTSERVER + redirect_url)
else:
self.assertRedirects(resp, redirect_url)
# Set SSL settings for test server
settings.SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL',
'https')
resp = self.client.get(url, HTTP_X_FORWARDED_PROTOCOL="https")
self.assertEqual(302, resp.status_code)
self.assertEqual('https://testserver:80%s' % redirect_url,
resp['location'])
# Restore settings
settings.SECURE_PROXY_SSL_HEADER = None
def get_version(version=None):
"Returns a PEP 386-compliant version number from VERSION."
version = get_complete_version(version)
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
main = get_main_version(version)
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return str(main + sub)
def get_git_changeset():
"""Returns a numeric identifier of the latest git changeset.
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
This value isn't guaranteed to be unique, but collisions are very unlikely,
so it's sufficient for generating the development version numbers.
"""
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
git_log = subprocess.Popen('git log --pretty=format:%ct --quiet -1 HEAD',
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=True, cwd=repo_dir, universal_newlines=True)
timestamp = git_log.communicate()[0]
try:
timestamp = datetime.datetime.utcfromtimestamp(int(timestamp))
except ValueError:
return None
return timestamp.strftime('%Y%m%d%H%M%S')
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
# it's called "original" because it will be replaced by a copy
attrs['class'] = 'hstore-original-textarea'
# get default HTML from AdminTextareaWidget
html = super(BaseAdminHStoreWidget, self).render(name, value, attrs)
# prepare template context
template_context = Context({
'field_name': name,
'STATIC_URL': settings.STATIC_URL,
'use_svg': django.VERSION >= (1, 9), # use svg icons if django >= 1.9
})
# get template object
template = get_template('happenings/hstore_%s_widget.html' % self.admin_style)
# render additional html
additional_html = template.render(template_context)
# append additional HTML and mark as safe
html = html + additional_html
html = mark_safe(html)
return html
def sql_table_creation_suffix(self):
suffix = []
if django.VERSION < (1, 7):
if self.connection.settings_dict['TEST_CHARSET']:
suffix.append('CHARACTER SET {0}'.format(
self.connection.settings_dict['TEST_CHARSET']))
if self.connection.settings_dict['TEST_COLLATION']:
suffix.append('COLLATE {0}'.format(
self.connection.settings_dict['TEST_COLLATION']))
else:
test_settings = self.connection.settings_dict['TEST']
if test_settings['CHARSET']:
suffix.append('CHARACTER SET %s' % test_settings['CHARSET'])
if test_settings['COLLATION']:
suffix.append('COLLATE %s' % test_settings['COLLATION'])
return ' '.join(suffix)
def test_good_data(self):
"""Upload a zip with a single file it it: 'sample.jpg'.
It gets assigned to a newly created gallery 'Test'."""
test_data = copy.copy(self.sample_form_data)
response = self.client.post('/admin/photologue/photo/upload_zip/', test_data)
# The redirect Location has changed in Django 1.9 - it used to be an absolute URI, now it returns
# a relative one.
if VERSION[0] == 1 and VERSION[1] <= 8:
location = 'http://testserver/admin/photologue/photo/'
else:
location = '..'
self.assertEqual(response['Location'], location)
self.assertQuerysetEqual(Gallery.objects.all(),
['<Gallery: This is a test title>'])
self.assertQuerysetEqual(Photo.objects.all(),
['<Photo: This is a test title 1>'])
# The photo is attached to the gallery.
gallery = Gallery.objects.get(title='This is a test title')
self.assertQuerysetEqual(gallery.photos.all(),
['<Photo: This is a test title 1>'])
def hijack_field(self, obj):
hijack_attributes = hijack_settings.HIJACK_URL_ALLOWED_ATTRIBUTES
if 'user_id' in hijack_attributes:
hijack_url = reverse('hijack:login_with_id', args=(obj.pk, ))
elif 'email' in hijack_attributes:
hijack_url = reverse('hijack:login_with_email', args=(obj.email, ))
else:
hijack_url = reverse('hijack:login_with_username', args=(obj.username, ))
button_template = get_template(hijack_admin_settings.HIJACK_BUTTON_TEMPLATE)
button_context = {
'hijack_url': hijack_url,
'username': str(obj),
}
if VERSION < (1, 8):
button_context = Context(button_context)
return button_template.render(button_context)
def dispatch(self, request, *args, **kwargs):
"""Override to check settings"""
if django.VERSION < (1, 10):
is_auth = request.user.is_authenticated()
else:
is_auth = request.user.is_authenticated
if not ADMIN_SHELL_ENABLE:
return HttpResponseNotFound("Not found: Django admin shell is not enabled")
elif is_auth is False or request.user.is_staff is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
return super(Shell, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs):
"""Override to check settings"""
if django.VERSION < (1, 10):
is_auth = request.user.is_authenticated()
else:
is_auth = request.user.is_authenticated
if not ADMIN_SHELL_ENABLE:
return HttpResponseNotFound("Not found: Django admin shell is not enabled")
elif is_auth is False or request.user.is_staff is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must have access the admin site")
elif ADMIN_SHELL_ONLY_DEBUG_MODE and settings.DEBUG is False:
return HttpResponseForbidden("Forbidden :Django admin shell require DEBUG mode")
elif ADMIN_SHELL_ONLY_FOR_SUPERUSER and request.user.is_superuser is False:
return HttpResponseForbidden("Forbidden: To access Django admin shell you must be superuser")
return super(Shell, self).dispatch(request, *args, **kwargs)
def clean(self):
email = self.cleaned_data.get('email')
password = self.cleaned_data.get('password')
if email and password:
if django.VERSION >= (1, 11):
self.user_cache = authenticate(self.request, email=email, password=password)
else:
self.user_cache = authenticate(email=email, password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
def filter(self, record):
"""
Adds information from the request to the logging *record*.
If certain information cannot be extracted from ``self.request``,
a hyphen ``'-'`` is substituted as a placeholder.
"""
request = self.request
# Basic
record.request_method = getattr(request, 'method', '-')
record.path_info = getattr(request, 'path_info', '-')
# User
user = getattr(request, 'user', None)
if django.VERSION < (1, 10) and user and not user.is_anonymous():
record.username = user.username
elif django.VERSION > (1, 10) and user and not user.is_anonymous:
record.username = user.username
else:
record.username = '-'
# Headers
META = getattr(request, 'META', {}) # NOQA: N806
record.remote_addr = META.get('REMOTE_ADDR', '-')
record.server_protocol = META.get('SERVER_PROTOCOL', '-')
record.http_user_agent = META.get('HTTP_USER_AGENT', '-')
return True
def _build_mock_request(self, user=None, get=None, post=None):
request = MagicMock()
if user:
request.user = user
if django.VERSION[:2] >= (1, 10):
# Django 1.10 made `User.is_authenticated` into a property for
# some reason.
request.user.is_authenticated.__get__ = MagicMock(return_value=True) # nopep8
else:
request.user.is_authenticated = MagicMock(return_value=True)
else:
request.user = AnonymousUser()
request.GET = {}
request.POST = {}
request.resolver_match.kwargs = {}
if get is not None:
request.GET.update(get)
if post is not None:
request.POST.update(post)
return request
def _build_mock_request(self, user=None, get=None, post=None):
request = MagicMock()
if user:
request.user = user
if django.VERSION[:2] >= (1, 10):
# Django 1.10 made `User.is_authenticated` into a property for
# some reason.
request.user.is_authenticated.__get__ = MagicMock(return_value=True) # nopep8
else:
request.user.is_authenticated = MagicMock(return_value=True)
else:
request.user = AnonymousUser()
request.GET = {}
request.POST = {}
request.resolver_match.kwargs = {}
if get is not None:
request.GET.update(get)
if post is not None:
request.POST.update(post)
return request
def get_names_and_managers(options):
if django.VERSION >= (1, 10):
# Django 1.10 onwards provides a `.managers` property on the Options.
return [
(manager.name, manager)
for manager
in options.managers
]
# For Django 1.8 and 1.9, use the three-tuple information provided
# by .concrete_managers and .abstract_managers
return [
(manager_info[1], manager_info[2])
for manager_info
in (options.concrete_managers + options.abstract_managers)
]
# field.rel is deprecated from 1.9 onwards
def _test(request, form_class):
passed = False
if request.POST:
form = form_class(request.POST)
if form.is_valid():
passed = True
else:
form = form_class()
t = _get_template(TEST_TEMPLATE)
if django.VERSION >= (1, 9):
return HttpResponse(
t.render(context=dict(passed=passed, form=form), request=request))
else:
return HttpResponse(
t.render(RequestContext(request, dict(passed=passed, form=form))))
def sql_table_creation_suffix(self):
suffix = []
if django.VERSION < (1, 7):
if self.connection.settings_dict['TEST_CHARSET']:
suffix.append('CHARACTER SET {0}'.format(
self.connection.settings_dict['TEST_CHARSET']))
if self.connection.settings_dict['TEST_COLLATION']:
suffix.append('COLLATE {0}'.format(
self.connection.settings_dict['TEST_COLLATION']))
else:
test_settings = self.connection.settings_dict['TEST']
if test_settings['CHARSET']:
suffix.append('CHARACTER SET %s' % test_settings['CHARSET'])
if test_settings['COLLATION']:
suffix.append('COLLATE %s' % test_settings['COLLATION'])
return ' '.join(suffix)
def test_angular_input_field(self):
my_form = SampleForm()
template = u'{% angular_input_field my_form.name model_name params %}'
context = {'my_form': my_form,
'model_name': 'yourname',
'params': {}}
# Django 1.10 changes the rendering of boolean attributes
if VERSION[1] > 9:
output = (u'<input class="form-control" id="id_name" '
u'maxlength="100" name="name" ng-model='
u'"yourname.fields.name" type="text" required />')
else:
output = (u'<input class="form-control" id="id_name" '
u'maxlength="100" name="name" ng-model='
u'"yourname.fields.name" required="true" type="text" />')
self.tag_test(template, context, output)
# repeat test, with bound form
my_form = SampleForm({'name': 'Joe Bloggs'})
self.tag_test(template, context, output)
def test_template_rendering(should_collect, django_elasticapm_client, client):
should_collect.return_value = False
with override_settings(**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.TracingMiddleware'])):
client.get(reverse('render-heavy-template'))
client.get(reverse('render-heavy-template'))
client.get(reverse('render-heavy-template'))
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 3
spans = transactions[0]['spans']
assert len(spans) == 2, [t['name'] for t in spans]
kinds = ['code', 'template.django']
assert set([t['type'] for t in spans]) == set(kinds)
assert spans[0]['type'] == 'code'
assert spans[0]['name'] == 'something_expensive'
assert spans[0]['parent'] == 0
assert spans[1]['type'] == 'template.django'
assert spans[1]['name'] == 'list_users.html'
assert spans[1]['parent'] is None
def test_template_rendering_django18_jinja2(should_collect, django_elasticapm_client, client):
should_collect.return_value = False
with override_settings(
TEMPLATES=TEMPLATES,
**middleware_setting(django.VERSION,
['elasticapm.contrib.django.middleware.TracingMiddleware'])
):
client.get(reverse('render-jinja2-template'))
client.get(reverse('render-jinja2-template'))
client.get(reverse('render-jinja2-template'))
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 3
spans = transactions[0]['spans']
assert len(spans) == 1, [t['name'] for t in spans]
kinds = ['template.jinja2']
assert set([t['type'] for t in spans]) == set(kinds)
assert spans[0]['type'] == 'template.jinja2'
assert spans[0]['name'] == 'jinja2_template.html'
assert spans[0]['parent'] is None
def value_to_db_datetime( self, value ):
if value is None:
return None
if( djangoVersion[0:2] <= ( 1, 3 ) ):
#DB2 doesn't support time zone aware datetime
if ( value.tzinfo is not None ):
raise ValueError( "Timezone aware datetime not supported" )
else:
return value
else:
if is_aware(value):
if settings.USE_TZ:
value = value.astimezone( utc ).replace( tzinfo=None )
else:
raise ValueError( "Timezone aware datetime not supported" )
return unicode( value )
def get_table_description( self, cursor, table_name ):
qn = self.connection.ops.quote_name
description = []
table_type = 'T'
if not _IS_JYTHON:
dbms_name='dbms_name'
schema = cursor.connection.get_current_schema()
if getattr(cursor.connection, dbms_name) != 'DB2':
sql = "SELECT TYPE FROM SYSCAT.TABLES WHERE TABSCHEMA='%(schema)s' AND TABNAME='%(table)s'" % {'schema': schema.upper(), 'table': table_name.upper()}
else:
sql = "SELECT TYPE FROM SYSIBM.SYSTABLES WHERE CREATOR='%(schema)s' AND NAME='%(table)s'" % {'schema': schema.upper(), 'table': table_name.upper()}
cursor.execute(sql)
table_type = cursor.fetchone()[0]
if table_type != 'X':
cursor.execute( "SELECT * FROM %s FETCH FIRST 1 ROWS ONLY" % qn( table_name ) )
if djangoVersion < (1, 6):
for desc in cursor.description:
description.append( [ desc[0].lower(), ] + desc[1:] )
else:
for desc in cursor.description:
description.append(FieldInfo(*[desc[0].lower(), ] + desc[1:]))
return description
def __init__( self, *args ):
super( DatabaseWrapper, self ).__init__( *args )
self.ops = DatabaseOperations( self )
if( djangoVersion[0:2] <= ( 1, 0 ) ):
self.client = DatabaseClient()
else:
self.client = DatabaseClient( self )
if( djangoVersion[0:2] <= ( 1, 2 ) ):
self.features = DatabaseFeatures()
else:
self.features = DatabaseFeatures( self )
self.creation = DatabaseCreation( self )
if( djangoVersion[0:2] >= ( 1, 8 ) ):
self.data_types=self.creation.data_types
self.data_type_check_constraints=self.creation.data_type_check_constraints
self.introspection = DatabaseIntrospection( self )
if( djangoVersion[0:2] <= ( 1, 1 ) ):
self.validation = DatabaseValidation()
else:
self.validation = DatabaseValidation( self )
self.databaseWrapper = Base.DatabaseWrapper()
# Method to check if connection is live or not.
def get_names_and_managers(options):
if django.VERSION >= (1, 10):
# Django 1.10 onwards provides a `.managers` property on the Options.
return [
(manager.name, manager)
for manager
in options.managers
]
# For Django 1.8 and 1.9, use the three-tuple information provided
# by .concrete_managers and .abstract_managers
return [
(manager_info[1], manager_info[2])
for manager_info
in (options.concrete_managers + options.abstract_managers)
]
# field.rel is deprecated from 1.9 onwards
def render(self, name, value, attrs=None):
if value is None:
value = ""
if VERSION < (1, 11):
final_attrs = self.build_attrs(attrs, name=name)
else:
final_attrs = self.build_attrs(attrs, {'name': name})
if "class" not in final_attrs:
final_attrs["class"] = ""
final_attrs["class"] += " wmd-input"
template = loader.get_template(self.template)
# Compatibility fix:
# see https://github.com/timmyomahony/django-pagedown/issues/42
context = {
"attrs": flatatt(final_attrs),
"body": conditional_escape(force_unicode(value)),
"id": final_attrs["id"],
"show_preview": self.show_preview,
}
context = Context(context) if VERSION < (1, 9) else context
return template.render(context)
def template_render(template, context=None, request=None):
"""
Passing Context or RequestContext to Template.render is deprecated in 1.9+,
see https://github.com/django/django/pull/3883 and
https://github.com/django/django/blob/1.9rc1/django/template/backends/django.py#L82-L84
:param template: Template instance
:param context: dict
:param request: Request instance
:return: rendered template as SafeText instance
"""
if django.VERSION < (1, 8) or isinstance(template, Template):
if request:
context = RequestContext(request, context)
else:
context = Context(context)
return template.render(context)
# backends template, e.g. django.template.backends.django.Template
else:
return template.render(context, request=request)
def assertRedirects(self, response, expected_url,
fetch_redirect_response=True,
**kwargs):
if django.VERSION >= (1, 7,):
super(TestCase, self).assertRedirects(
response,
expected_url,
fetch_redirect_response=fetch_redirect_response,
**kwargs)
elif fetch_redirect_response:
super(TestCase, self).assertRedirects(
response,
expected_url,
**kwargs)
else:
self.assertEqual(302, response.status_code)
actual_url = response['location']
if expected_url[0] == '/':
parts = list(urlparse(actual_url))
parts[0] = parts[1] = ''
actual_url = urlunparse(parts)
self.assertEqual(expected_url, actual_url)
def _test(request, form_class):
passed = False
if request.POST:
form = form_class(request.POST)
if form.is_valid():
passed = True
else:
form = form_class()
t = _get_template(TEST_TEMPLATE)
if django.VERSION >= (1, 9):
return HttpResponse(
t.render(context=dict(passed=passed, form=form), request=request))
else:
return HttpResponse(
t.render(RequestContext(request, dict(passed=passed, form=form))))