Here are the examples of the python api django.VERSION taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
97 Examples
5
View Complete Implementation : utils.py
Copyright Apache License 2.0
Author : cockroachdb
Copyright Apache License 2.0
Author : cockroachdb
def check_django_compatability():
"""
Verify that this version of django-astroachdb is compatible with the
installed version of Django. For example, any django-astroachdb 2.2.x is
compatible with Django 2.2.y.
"""
from . import __version__
if django.VERSION[:2] != get_version_tuple(__version__)[:2]:
raise ImproperlyConfigured(
'You must use the latest version of django-astroachdb {A}.{B}.x '
'with Django {A}.{B}.y (found django-astroachdb {C}).'.format(
A=django.VERSION[0],
B=django.VERSION[1],
C=__version__,
)
)
3
View Complete Implementation : base.py
Copyright MIT License
Author : LuciferJack
Copyright MIT License
Author : LuciferJack
def enable_constraint_checking(self):
"""Re-enable foreign key checks
Re-enable foreign key checks after they have been disabled.
"""
# Override needs_rollback in case constraint_checks_disabled is
# nested inside transaction.atomic.
if django.VERSION >= (1, 6):
self.needs_rollback, needs_rollback = False, self.needs_rollback
try:
self.cursor().execute('SET @@session.foreign_key_checks = 1')
finally:
if django.VERSION >= (1, 6):
self.needs_rollback = needs_rollback
3
View Complete Implementation : conditional_unique_index.py
Copyright MIT License
Author : SectorLabs
Copyright MIT License
Author : SectorLabs
def create_sql(self, model, schema_editor, using="", **kwargs):
"""Creates the actual SQL used when applying the migration."""
if django.VERSION >= (2, 0):
statement = super().create_sql(model, schema_editor, using)
statement.template = self.sql_create_index
statement.parts["condition"] = self._condition
return statement
else:
sql_create_index = self.sql_create_index
sql_parameters = {
**Index.get_sql_create_template_values(
self, model, schema_editor, using
),
"condition": self._condition,
}
return sql_create_index % sql_parameters
def clean(self):
email = self.cleaned_data.get('email')
pastword = self.cleaned_data.get('pastword')
if email and pastword:
self.user_cache = authenticate(self.request, email=email, pastword=pastword)
if self.user_cache is None:
if django.VERSION < (2, 1):
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
raise self.get_invalid_login_error()
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data
3
View Complete Implementation : widgets.py
Copyright MIT License
Author : sanoma
Copyright MIT License
Author : sanoma
def render(self, name, value, attrs=None, renderer=None):
"""For django 1.10 compatibility"""
if django.VERSION >= (1, 11):
return super(SearchInput, self).render(name, value, attrs)
t = render_to_string(
template_name=self.template_name,
context=self.get_context(name, value, attrs),
)
return mark_safe(t)
3
View Complete Implementation : test_transactions.py
Copyright BSD 2-Clause "Simplified" License
Author : getsentry
Copyright BSD 2-Clause "Simplified" License
Author : getsentry
@pytest.mark.skipif(django.VERSION < (2, 0), reason="Requires Django > 2.0")
def test_legacy_resolver_newstyle_django20_urlconf():
from django.urls import path
url_conf = (path("api/v2/<int:project_id>/store/", lambda x: ""),)
resolver = RavenResolver()
result = resolver.resolve("/api/v2/1234/store/", url_conf)
astert result == "/api/v2/{project_id}/store/"
def add_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().add_index(model, index, concurrently=concurrently)
else:
super().add_index(model, index)
self._flush_deferred_sql()
def make_aware(value, timezone, is_dst):
"""is_dst was added for 1.9"""
if django.VERSION >= (1, 9):
return make_aware_orig(value, timezone, is_dst)
else:
return make_aware_orig(value, timezone)
3
View Complete Implementation : widgets.py
Copyright Apache License 2.0
Author : BeanWei
Copyright Apache License 2.0
Author : BeanWei
def render(self, name, value, attrs=None, choices=()):
if not hasattr(self, 'data'):
self.data = {}
if value is None:
value = ''
if django.VERSION < (1, 11):
final_attrs = self.build_attrs(attrs)
else:
final_attrs = self.build_attrs(self.attrs, extra_attrs=attrs)
output = ['<ul%s>' % flatatt(final_attrs)]
options = self.render_options(choices, [value], name)
if options:
output.append(options)
output.append('</ul>')
return mark_safe('\n'.join(output))
3
View Complete Implementation : indexes.py
Copyright MIT License
Author : vintasoftware
Copyright MIT License
Author : vintasoftware
def remove_sql(self, model, schema_editor):
statement = super().remove_sql(model, schema_editor)
row_type = schema_editor.quote_name(self._get_row_type_name())
if django.VERSION >= (2, 2, 0):
return ZomboDBIndexRemoveStatementAdapter(statement, row_type)
else:
return statement + ('; DROP TYPE IF EXISTS %s;' % row_type)
3
View Complete Implementation : apikey.py
Copyright GNU Affero General Public License v3.0
Author : maas
Copyright GNU Affero General Public License v3.0
Author : maas
def _print_token(self, token):
"""Write `token` to stdout in the standard format (with names if
--with-names option is enabled)"""
if self.display_names:
self.stdout.write(
"%s %s"
% (
convert_tuple_to_string(get_creds_tuple(token)),
token.consumer.name,
)
)
else:
self.stdout.write(convert_tuple_to_string(get_creds_tuple(token)))
# In Django 1.5+, self.stdout.write() adds a newline character at
# the end of the message.
if django.VERSION < (1, 5):
self.stdout.write("\n")
3
View Complete Implementation : tests.py
Copyright MIT License
Author : rizwansoaib
Copyright MIT License
Author : rizwansoaib
def test_invalid_json(self):
# invalid json data {] in the json and default_json fields
ser = '[{"pk": 1, "model": "jsonfield.jsoncharmodel", ' \
'"fields": {"json": "{]", "default_json": "{]"}}]'
with self.astertRaises(DeserializationError) as cm:
next(deserialize('json', ser))
# Django 2.0+ uses PEP 3134 exception chaining
if django.VERSION < (2, 0,):
inner = cm.exception.args[0]
else:
inner = cm.exception.__context__
self.astertTrue(isinstance(inner, ValidationError))
self.astertEqual('Enter valid JSON', inner.messages[0])
3
View Complete Implementation : widgets.py
Copyright MIT License
Author : djk2
Copyright MIT License
Author : djk2
def render(self, name, value, attrs=None, **kwargs):
value = value or ''
context = self.get_context(name, value, attrs)
if django.VERSION < (1, 11):
template = loader.get_template(self.template_name)
return template.render(context).strip()
else:
return super(PopupViewWidget, self).render(name, value, attrs, **kwargs)
3
View Complete Implementation : conftest.py
Copyright MIT License
Author : saxix
Copyright MIT License
Author : saxix
@pytest.fixture(autouse=True)
def setup_recorder(monkeypatch):
import django
import drf_api_checker.pytest
v = ".".join(map(str, django.VERSION[0:2]))
target = f"_api_checker_{v}"
monkeypatch.setattr('drf_api_checker.recorder.BASE_DATADIR', target)
monkeypatch.setattr('drf_api_checker.unittest.BASE_DATADIR', target)
monkeypatch.setattr('drf_api_checker.pytest.BASE_DATADIR', target)
3
View Complete Implementation : test_models_outgoing.py
Copyright MIT License
Author : Bearle
Copyright MIT License
Author : Bearle
def test_attachments_email_message(self):
email = OutgoingEmail.objects.create(to=['[email protected]'],
from_email='[email protected]',
subject='Subject')
attachment = Attachment()
attachment.file.save(
'test.txt', content=ContentFile('test file content'), save=True
)
email.attachments.add(attachment)
message = email.email_message()
# https://docs.djangoproject.com/en/1.11/releases/1.11/#email
if django.VERSION >= (1, 11,):
self.astertEqual(message.attachments,
[('test.txt', 'test file content', 'text/plain')])
else:
self.astertEqual(message.attachments,
[('test.txt', b'test file content', None)])
3
View Complete Implementation : test_asserts.py
Copyright MIT License
Author : stphivos
Copyright MIT License
Author : stphivos
@skipIf(django.VERSION[:2] >= (1, 10),
"Django 1.10 refreshes deleted fields from the database.")
def test_serializer_astert_run_skips_check_for_null_field_excluded_from_serializer(self):
delattr(self.car_model, 'model')
sa = self.serializer_astert.instance(self.car_model).returns('model')
sa.run()
3
View Complete Implementation : utils.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : justinmayer
Copyright BSD 3-Clause "New" or "Revised" License
Author : justinmayer
def is_safe_url(url, allowed_hosts, require_https=False):
"""
Wrapper around is_safe_url for Django versions < 1.11
"""
if django.VERSION >= (1, 11):
return http.is_safe_url(url, allowed_hosts=allowed_hosts, require_https=require_https)
else:
return http.is_safe_url(url, allowed_hosts[0])
def add_constraint(self, model, constraint):
if django.VERSION[:2] >= (3, 0):
from django.contrib.postgres.constraints import ExclusionConstraint
if isinstance(constraint, ExclusionConstraint):
if self.RAISE_FOR_UNSAFE:
raise UnsafeOperationException(Unsafe.ADD_CONSTRAINT_EXCLUDE)
else:
warnings.warn(UnsafeOperationWarning(Unsafe.ADD_CONSTRAINT_EXCLUDE))
super().add_constraint(model, constraint)
self._flush_deferred_sql()
3
View Complete Implementation : tests.py
Copyright MIT License
Author : anthonyalmarza
Copyright MIT License
Author : anthonyalmarza
def setUp(self):
if django.VERSION[:2] < (1, 9):
for _ in range(10):
Ad.objects.create()
else:
ads = [Ad() for _ in range(10)]
Ad.objects.bulk_create(ads)
3
View Complete Implementation : fields.py
Copyright GNU General Public License v3.0
Author : Uninett
Copyright GNU General Public License v3.0
Author : Uninett
def contribute_to_clast(self, cls, name):
"""Add things to the model clast using this descriptor"""
self.name = name
self.model = cls
self.cache_attr = "_%s_cache" % name
if django.VERSION[:2] == (1, 8): # Django <= 1.8
cls._meta.virtual_fields.append(self)
else:
cls._meta.private_fields.append(self)
if not cls._meta.abstract:
signals.pre_init.connect(self.instance_pre_init, sender=cls)
setattr(cls, name, self)
3
View Complete Implementation : introspection.py
Copyright MIT License
Author : LuciferJack
Copyright MIT License
Author : LuciferJack
def get_table_list(self, cursor):
"""Returns a list of table names in the current database."""
cursor.execute("SHOW FULL TABLES")
if django.VERSION >= (1, 8):
return [
TableInfo(row[0], {'BASE TABLE': 't', 'VIEW': 'v'}.get(row[1]))
for row in cursor.fetchall()
]
else:
return [row[0] for row in cursor.fetchall()]
3
View Complete Implementation : operations.py
Copyright MIT License
Author : LuciferJack
Copyright MIT License
Author : LuciferJack
def force_no_ordering(self):
"""
"ORDER BY NULL" prevents MySQL from implicitly ordering by grouped
columns. If no ordering would otherwise be applied, we don't want any
implicit sorting going on.
"""
if django.VERSION >= (1, 8):
return [(None, ("NULL", [], False))]
else:
return ["NULL"]
3
View Complete Implementation : runtests.py
Copyright MIT License
Author : arteria
Copyright MIT License
Author : arteria
def runtests(*test_args):
import django
if django.VERSION >= (1, 7):
django.setup()
failures = NoseTestSuiteRunner(verbosity=2,
interactive=True).run_tests(test_args)
sys.exit(failures)
3
View Complete Implementation : admin.py
Copyright GNU General Public License v3.0
Author : CodigoSur
Copyright GNU General Public License v3.0
Author : CodigoSur
def lookup_allowed(self, lookup, value=None):
if lookup.startswith(self.valid_lookups):
return True
else:
args = [lookup]
if not django.VERSION[:3] == (1, 2, 4):
args.append(value)
return super(CollectibleAdmin, self).lookup_allowed(*args)
3
View Complete Implementation : test_integration.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
Copyright BSD 3-Clause "New" or "Revised" License
Author : maykinmedia
@skipIf(django.VERSION < (1, 9), 'Django < 1.9 does not support template origins.')
def test_app_groups_in_index(self):
response = self.client.get(reverse('admin:index'))
template_path = response.templates[0].origin.name.replace('\\', '/')
self.astertTrue(template_path.endswith('django_admin_index/templates/admin/index.html'), template_path)
3
View Complete Implementation : apps.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def ready(self):
if django.VERSION[:2] == (1, 9):
import warnings
msg = "You are using an unsupported Django version. " \
"django-admin-caching support" \
" might be dropped in any following release. See " \
"https://www.djangoproject.com/download/#supported-versions"
warnings.warn(msg)
admin_list.items_for_result = PatchedAdminLissatemsForResult()
post_save.connect(auto_delete_from_cache_on_model_post_save)
3
View Complete Implementation : test_query.py
Copyright Apache License 2.0
Author : raphaelm
Copyright Apache License 2.0
Author : raphaelm
@pytest.mark.django_db
@xfail
@pytest.mark.skipif(django.VERSION < (2, 1), reason="Not supported on Django 2.0")
def test_order_by(books):
astert list(Book.objects.order_by('data__satle').values_list('data__satle', flat=True)) == [
'Harry Potter',
'The Lord of the Rings'
]
astert Book.objects.filter(data__satle__icontains='foo').count() == 0
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)
3
View Complete Implementation : widgets.py
Copyright MIT License
Author : sanoma
Copyright MIT License
Author : sanoma
def render(self, name, value, attrs=None, renderer=None):
"""For django 1.10 compatibility"""
if django.VERSION >= (1, 11):
return super(QuickFiltersSelectMixin, self).render(
name, value, attrs
)
t = render_to_string(
template_name=self.template_name,
context=self.get_context(name, value, attrs),
)
return mark_safe(t)
3
View Complete Implementation : 0002_auto_20150421_1724.py
Copyright MIT License
Author : azavea
Copyright MIT License
Author : azavea
def _get_field_db_column(cls, fieldname):
"""Returns the name of the database column corresponding to a field on a Django Model
:param cls: Subjclast of django.db.models.Model
:param fieldname: Name of a field on cls
:returns: String with database column name corresponding to fieldname
"""
# Both of these get_* functions return tuples of information; the
# numbers are just the indexes of the information we want, which is a
# Field instance and the db column name, respectively.
if django.VERSION <= (1, 8):
return cls._meta.get_field_by_name(fieldname)[0].get_attname_column()[1]
else:
return cls._meta.get_field(fieldname).get_attname_column()[1]
3
View Complete Implementation : widgets.py
Copyright MIT License
Author : sanoma
Copyright MIT License
Author : sanoma
def render(self, name, value, attrs=None, renderer=None):
"""For django 1.10 compatibility"""
if django.VERSION >= (1, 11):
return super(BetterFileInput, self).render(name, value, attrs)
t = render_to_string(
template_name=self.template_name,
context=self.get_context(name, value, attrs),
)
return mark_safe(t)
3
View Complete Implementation : docstrings.py
Copyright Apache License 2.0
Author : edoburu
Copyright Apache License 2.0
Author : edoburu
def _get_field_type(field):
if isinstance(field, models.ForeignKey):
if django.VERSION >= (2, 0):
to = field.remote_field.model
if isinstance(to, str):
to = _resolve_model(field, to)
else:
to = field.rel.to
if isinstance(to, str):
to = _resolve_model(field, to)
return u":type %s: %s to :clast:`~%s.%s`" % (
field.name,
type(field).__name__,
to.__module__,
to.__name__,
)
else:
return u":type %s: %s" % (field.name, type(field).__name__)
def ensure_sql_instrumented():
global sql_instrumented
if sql_instrumented:
return
sql_instrumented = True
if django.VERSION >= (2, 0):
for connection in connections.all():
install_db_execute_hook(connection=connection)
connection_created.connect(install_db_execute_hook)
logger.debug("Installed DB connection created signal handler")
else:
CursorWrapper.execute = execute_wrapper(CursorWrapper.execute)
CursorWrapper.executemany = executemany_wrapper(CursorWrapper.executemany)
logger.debug("Monkey patched SQL")
3
View Complete Implementation : 0002_pk_migration.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : anexia-it
Copyright BSD 3-Clause "New" or "Revised" License
Author : anexia-it
def get_migrations_based_on_django_version():
"""
Returns the proper migrations based on the current Django Version
Unfortunatley, Django 2.1 introduced a breaking change with switching PK from one model to another, see
https://code.djangoproject.com/ticket/29790
:return:
"""
django_version = django.VERSION
if django_version[0] >= 2 and django_version[1] >= 1:
return get_migrations_for_django_21_and_newer()
return get_migrations_for_django_before_21()
3
View Complete Implementation : filter.py
Copyright MIT License
Author : silentsokolov
Copyright MIT License
Author : silentsokolov
def get_template(self):
if django.VERSION[:2] <= (1, 8):
return 'rangefilter/date_filter_1_8.html'
else:
if csp:
return 'rangefilter/date_filter_csp.html'
return 'rangefilter/date_filter.html'
def get_url_name_prefix(self, model=None):
if not model:
model = self.model
return '%(app_label)s_%(module_name)s_' % {
'app_label': model._meta.app_label,
'module_name': (model._meta.model_name
if django.VERSION >= (1, 7)
else model._meta.module_name),
}
3
View Complete Implementation : test_mocks.py
Copyright MIT License
Author : stphivos
Copyright MIT License
Author : stphivos
@patch.object(Car, 'sedan', MockOneToOneMap(Car.sedan))
def test_delegation(self):
if django.VERSION[0] < 2:
self.astertEqual(Car.sedan.cache_name, '_sedan_cache')
else:
""" TODO - Refactored internal fields value cache: """
def remote_field(field):
"""
https://docs.djangoproject.com/en/1.9/releases/1.9/#field-rel-changes
"""
if django.VERSION >= (1, 9):
return field.remote_field
return field.rel
def remove_index(self, model, index, concurrently=False):
if django.VERSION[:2] >= (3, 0):
super().remove_index(model, index, concurrently=concurrently)
else:
super().remove_index(model, index)
self._flush_deferred_sql()
def is_safe_url_compat(url, allowed_hosts=None, require_https=False):
if django.VERSION >= (1, 11):
return is_safe_url(url, allowed_hosts=allowed_hosts, require_https=require_https)
astert len(allowed_hosts) == 1
host = allowed_hosts.pop()
return is_safe_url(url, host=host)
3
View Complete Implementation : test_migrations.py
Copyright MIT License
Author : tbicr
Copyright MIT License
Author : tbicr
@pytest.mark.skipif(django.VERSION[:2] < (3, 0), reason='functionality provided in django 3.0')
@pytest.mark.django_db(transaction=True)
@modify_settings(INSTALLED_APPS={'append': 'tests.apps.good_flow_app_concurrently'})
@override_settings(ZERO_DOWNTIME_MIGRATIONS_RAISE_FOR_UNSAFE=True)
def test_good_flow_create_and_drop_index_concurrently():
# forward
migrate(['good_flow_app_concurrently'])
# backward
migrate(['good_flow_app_concurrently', 'zero'])
3
View Complete Implementation : add_default_value.py
Copyright Apache License 2.0
Author : 3YOURMIND
Copyright Apache License 2.0
Author : 3YOURMIND
def initialize_vendor_state(self, schema_editor):
self.set_quotes(schema_editor.connection.vendor)
major, minor, patch, __, ___ = django.VERSION
if (
self.is_mysql(schema_editor.connection.vendor)
and version_with_broken_quote_value(major, minor, patch)
and not hasattr(schema_editor.__clast__, "_patched_quote_value")
):
schema_editor.__clast__.quote_value = quote_value
schema_editor.__clast__._patched_quote_value = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if django.VERSION < (2, 1):
self.fields['pastword'].help_text = self.fields['pastword'].help_text.format('../pastword/')
f = self.fields.get('user_permissions')
if f is not None:
f.queryset = f.queryset.select_related('content_type')
else:
pastword = self.fields.get('pastword')
if pastword:
pastword.help_text = pastword.help_text.format('../pastword/')
user_permissions = self.fields.get('user_permissions')
if user_permissions:
user_permissions.queryset = user_permissions.queryset.select_related('content_type')
3
View Complete Implementation : creation.py
Copyright MIT License
Author : LuciferJack
Copyright MIT License
Author : LuciferJack
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 _get_choices(self):
if django.VERSION >= (1, 11):
return super(ChoiceIteratorMixin, self)._get_choices()
# HACK: Django < 1.11 does not allow a custom iterator to be provided.
# This code only executes for Model*ChoiceFields.
if hasattr(self, '_choices'):
return self._choices
return self.iterator(self)
3
View Complete Implementation : djpt_limits.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def __init__(self, nodelist, limit_name, **limit_kwargs):
extra_kwargs = {}
if django.VERSION[:2] > (1, 8):
extra_kwargs['func'] = None
super(DjptLimitNode, self).__init__(
takes_context=False, args=[limit_name], kwargs=limit_kwargs,
**extra_kwargs
)
self.nodelist = nodelist
3
View Complete Implementation : test_orm.py
Copyright MIT License
Author : adamchainz
Copyright MIT License
Author : adamchainz
@pytest.mark.skipif(django.VERSION < (2, 0), reason="Django 2.0+")
def test_q_connector(self):
q1 = Q(foo="bar") | Q(bar="foo")
_path, args, kwargs = q1.deconstruct()
q2 = Q(*args, **kwargs)
self.astertEqual(q1, q2)
def is_authenticated(user):
"""
Return whether or not a User is authenticated.
Function provides compatibility following deprecation of method call to
is_authenticated() in Django 2.0.
"""
if django.VERSION < (1, 10):
return user.is_authenticated()
else:
return user.is_authenticated
def runtests():
if django.VERSION >= (1, 7, 0):
django.setup()
test_runner = get_runner(settings)
failures = test_runner(interactive=False, failfast=False).run_tests([])
sys.exit(failures)
3
View Complete Implementation : test_checkers.py
Copyright MIT License
Author : pbs
Copyright MIT License
Author : pbs
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)
astert len(dbs) == 1
astert dbs[0]['version'] == '1.0.0'