Replaced set([foo, ...]) by {foo, ...} literals. Refs PR 3282.

Thanks Collin Anderson for the review.
This commit is contained in:
Thomas Chaumeny 2014-09-26 14:31:50 +02:00 committed by Loic Bistuer
parent caf5cd7ba7
commit b2aad7b836
37 changed files with 123 additions and 122 deletions

View File

@ -275,7 +275,7 @@ class ChangeList(object):
# ordering fields so we can guarantee a deterministic order across all
# database backends.
pk_name = self.lookup_opts.pk.name
if not (set(ordering) & set(['pk', '-pk', pk_name, '-' + pk_name])):
if not (set(ordering) & {'pk', '-pk', pk_name, '-' + pk_name}):
# The two sets do not intersect, meaning the pk isn't present. So
# we add it.
ordering.append('-pk')

View File

@ -71,8 +71,8 @@ class BaseModelBackendTest(object):
# reloading user to purge the _perm_cache
user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertEqual(user.get_all_permissions() == set(['auth.test']), True)
self.assertEqual(user.get_group_permissions(), set([]))
self.assertEqual(user.get_all_permissions() == {'auth.test'}, True)
self.assertEqual(user.get_group_permissions(), set())
self.assertEqual(user.has_module_perms('Group'), False)
self.assertEqual(user.has_module_perms('auth'), True)
@ -81,7 +81,7 @@ class BaseModelBackendTest(object):
perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
user.user_permissions.add(perm)
user = self.UserModel._default_manager.get(pk=self.user.pk)
self.assertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3']))
self.assertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'})
self.assertEqual(user.has_perm('test'), False)
self.assertEqual(user.has_perm('auth.test'), True)
self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
@ -91,9 +91,9 @@ class BaseModelBackendTest(object):
group.permissions.add(perm)
user.groups.add(group)
user = self.UserModel._default_manager.get(pk=self.user.pk)
exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'])
exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'}
self.assertEqual(user.get_all_permissions(), exp)
self.assertEqual(user.get_group_permissions(), set(['auth.test_group']))
self.assertEqual(user.get_group_permissions(), {'auth.test_group'})
self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)
user = AnonymousUser()
@ -108,9 +108,9 @@ class BaseModelBackendTest(object):
user.user_permissions.add(perm)
self.assertEqual(user.has_perm('auth.test', 'object'), False)
self.assertEqual(user.get_all_permissions('object'), set([]))
self.assertEqual(user.get_all_permissions('object'), set())
self.assertEqual(user.has_perm('auth.test'), True)
self.assertEqual(user.get_all_permissions(), set(['auth.test']))
self.assertEqual(user.get_all_permissions(), {'auth.test'})
def test_anonymous_has_no_permissions(self):
"""
@ -129,9 +129,9 @@ class BaseModelBackendTest(object):
user.groups.add(group)
group.permissions.add(group_perm)
self.assertEqual(backend.get_all_permissions(user), set(['auth.test_user', 'auth.test_group']))
self.assertEqual(backend.get_user_permissions(user), set(['auth.test_user', 'auth.test_group']))
self.assertEqual(backend.get_group_permissions(user), set(['auth.test_group']))
self.assertEqual(backend.get_all_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_user_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_group_permissions(user), {'auth.test_group'})
user.is_anonymous = lambda: True
@ -156,9 +156,9 @@ class BaseModelBackendTest(object):
user.groups.add(group)
group.permissions.add(group_perm)
self.assertEqual(backend.get_all_permissions(user), set(['auth.test_user', 'auth.test_group']))
self.assertEqual(backend.get_user_permissions(user), set(['auth.test_user', 'auth.test_group']))
self.assertEqual(backend.get_group_permissions(user), set(['auth.test_group']))
self.assertEqual(backend.get_all_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_user_permissions(user), {'auth.test_user', 'auth.test_group'})
self.assertEqual(backend.get_group_permissions(user), {'auth.test_group'})
user.is_active = False
user.save()
@ -367,14 +367,14 @@ class RowlevelBackendTest(TestCase):
self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False)
def test_get_all_permissions(self):
self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['simple']))
self.assertEqual(self.user2.get_all_permissions(TestObj()), set(['simple', 'advanced']))
self.assertEqual(self.user2.get_all_permissions(), set([]))
self.assertEqual(self.user1.get_all_permissions(TestObj()), {'simple'})
self.assertEqual(self.user2.get_all_permissions(TestObj()), {'simple', 'advanced'})
self.assertEqual(self.user2.get_all_permissions(), set())
def test_get_group_permissions(self):
group = Group.objects.create(name='test_group')
self.user3.groups.add(group)
self.assertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm']))
self.assertEqual(self.user3.get_group_permissions(TestObj()), {'group_perm'})
class AnonymousUserBackendTest(TestCase):
@ -405,7 +405,7 @@ class AnonymousUserBackendTest(TestCase):
self.assertEqual(self.user1.has_module_perms("app2"), False)
def test_get_all_permissions(self):
self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon']))
self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'})
@skipIfCustomUser

View File

@ -31,7 +31,7 @@ class MySQLOperations(DatabaseOperations, BaseSpatialOperations):
'within': 'MBRWithin',
}
gis_terms = set(geometry_functions) | set(['isnull'])
gis_terms = set(geometry_functions) | {'isnull'}
def geo_db_type(self, f):
return f.geom_type

View File

@ -137,7 +137,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
}
geometry_functions.update(distance_functions)
gis_terms = set(['isnull'])
gis_terms = {'isnull'}
gis_terms.update(geometry_functions)
truncate_params = {'relate': None}

View File

@ -177,7 +177,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
}
# Creating a dictionary lookup of all GIS terms for PostGIS.
self.gis_terms = set(['isnull'])
self.gis_terms = {'isnull'}
self.gis_terms.update(self.geometry_operators)
self.gis_terms.update(self.geometry_functions)

View File

@ -134,7 +134,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
super(DatabaseOperations, self).__init__(connection)
# Creating the GIS terms dictionary.
self.gis_terms = set(['isnull'])
self.gis_terms = {'isnull'}
self.gis_terms.update(self.geometry_functions)
@cached_property

View File

@ -204,7 +204,7 @@ class Geo3DTest(TestCase):
union = City3D.objects.aggregate(Union('point'))['point__union']
self.assertTrue(union.hasz)
# Ordering of points in the resulting geometry may vary between implementations
self.assertSetEqual(set([p.ewkt for p in ref_union]), set([p.ewkt for p in union]))
self.assertSetEqual({p.ewkt for p in ref_union}, {p.ewkt for p in union})
def test_extent(self):
"""

View File

@ -113,9 +113,9 @@ class RelatedGeoModelTest(TestCase):
# Ordering of points in the result of the union is not defined and
# implementation-dependent (DB backend, GEOS version)
self.assertSetEqual(set([p.ewkt for p in ref_u1]), set([p.ewkt for p in u1]))
self.assertSetEqual(set([p.ewkt for p in ref_u2]), set([p.ewkt for p in u2]))
self.assertSetEqual(set([p.ewkt for p in ref_u1]), set([p.ewkt for p in u3]))
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u1})
self.assertSetEqual({p.ewkt for p in ref_u2}, {p.ewkt for p in u2})
self.assertSetEqual({p.ewkt for p in ref_u1}, {p.ewkt for p in u3})
def test05_select_related_fk_to_subclass(self):
"Testing that calling select_related on a query over a model with an FK to a model subclass works"

View File

@ -64,7 +64,7 @@ def make_msgid(idstring=None):
# Header names that contain structured address data (RFC #5322)
ADDRESS_HEADERS = set([
ADDRESS_HEADERS = {
'from',
'sender',
'reply-to',
@ -76,7 +76,7 @@ ADDRESS_HEADERS = set([
'resent-to',
'resent-cc',
'resent-bcc',
])
}
def forbid_multi_line_headers(name, val, encoding):

View File

@ -44,9 +44,9 @@ def handle_extensions(extensions=('html',), ignored=('py',)):
would result in an extension list: ['.js', '.txt', '.xhtml']
>>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py'])
set(['.html', '.js'])
{'.html', '.js'}
>>> handle_extensions(['.html, txt,.tpl'])
set(['.html', '.tpl', '.txt'])
{'.html', '.tpl', '.txt'}
"""
ext_list = []
for ext in extensions:

View File

@ -1351,10 +1351,10 @@ class BaseDatabaseIntrospection(object):
for app_config in apps.get_app_configs():
all_models.extend(router.get_migratable_models(app_config, self.connection.alias))
tables = list(map(self.table_name_converter, tables))
return set([
return {
m for m in all_models
if self.table_name_converter(m._meta.db_table) in tables
])
}
def sequence_list(self):
"Returns a list of information about all DB sequences for all models in all apps."

View File

@ -873,13 +873,13 @@ class MigrationAutodetector(object):
# We run the old version through the field renames to account for those
old_value = old_model_state.options.get(option_name) or set()
if old_value:
old_value = set([
old_value = {
tuple(
self.renamed_fields.get((app_label, model_name, n), n)
for n in unique
)
for unique in old_value
])
}
new_value = new_model_state.options.get(option_name) or set()
if new_value:

View File

@ -207,10 +207,10 @@ class MigrationWriter(object):
def serialize_deconstructed(cls, path, args, kwargs):
module, name = path.rsplit(".", 1)
if module == "django.db.models":
imports = set(["from django.db import models"])
imports = {"from django.db import models"}
name = "models.%s" % name
else:
imports = set(["import %s" % module])
imports = {"import %s" % module}
name = path
strings = []
for arg in args:
@ -246,6 +246,7 @@ class MigrationWriter(object):
imports.update(item_imports)
strings.append(item_string)
if isinstance(value, set):
# Don't use the literal "{%s}" as it doesn't support empty set
format = "set([%s])"
elif isinstance(value, tuple):
# When len(value)==0, the empty tuple should be serialized as
@ -272,20 +273,20 @@ class MigrationWriter(object):
value_repr = repr(value)
if isinstance(value, datetime_safe.datetime):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
return value_repr, {"import datetime"}
# Dates
elif isinstance(value, datetime.date):
value_repr = repr(value)
if isinstance(value, datetime_safe.date):
value_repr = "datetime.%s" % value_repr
return value_repr, set(["import datetime"])
return value_repr, {"import datetime"}
# Times
elif isinstance(value, datetime.time):
value_repr = repr(value)
return value_repr, set(["import datetime"])
return value_repr, {"import datetime"}
# Settings references
elif isinstance(value, SettingsReference):
return "settings.%s" % value.setting_name, set(["from django.conf import settings"])
return "settings.%s" % value.setting_name, {"from django.conf import settings"}
# Simple types
elif isinstance(value, six.integer_types + (float, bool, type(None))):
return repr(value), set()
@ -303,7 +304,7 @@ class MigrationWriter(object):
return value_repr, set()
# Decimal
elif isinstance(value, decimal.Decimal):
return repr(value), set(["from decimal import Decimal"])
return repr(value), {"from decimal import Decimal"}
# Django fields
elif isinstance(value, models.Field):
attr_name, path, args, kwargs = value.deconstruct()
@ -317,7 +318,7 @@ class MigrationWriter(object):
if getattr(value, "__self__", None) and isinstance(value.__self__, type):
klass = value.__self__
module = klass.__module__
return "%s.%s.%s" % (module, klass.__name__, value.__name__), set(["import %s" % module])
return "%s.%s.%s" % (module, klass.__name__, value.__name__), {"import %s" % module}
# Further error checking
if value.__name__ == '<lambda>':
raise ValueError("Cannot serialize function: lambda")
@ -326,7 +327,7 @@ class MigrationWriter(object):
# Python 3 is a lot easier, and only uses this branch if it's not local.
if getattr(value, "__qualname__", None) and getattr(value, "__module__", None):
if "<" not in value.__qualname__: # Qualname can include <locals>
return "%s.%s" % (value.__module__, value.__qualname__), set(["import %s" % value.__module__])
return "%s.%s" % (value.__module__, value.__qualname__), {"import %s" % value.__module__}
# Python 2/fallback version
module_name = value.__module__
# Make sure it's actually there and not an unbound method
@ -341,7 +342,7 @@ class MigrationWriter(object):
"For more information, see "
"https://docs.djangoproject.com/en/dev/topics/migrations/#serializing-values"
% (value.__name__, module_name))
return "%s.%s" % (module_name, value.__name__), set(["import %s" % module_name])
return "%s.%s" % (module_name, value.__name__), {"import %s" % module_name}
# Classes
elif isinstance(value, type):
special_cases = [
@ -355,7 +356,7 @@ class MigrationWriter(object):
if module == six.moves.builtins.__name__:
return value.__name__, set()
else:
return "%s.%s" % (module, value.__name__), set(["import %s" % module])
return "%s.%s" % (module, value.__name__), {"import %s" % module}
# Other iterables
elif isinstance(value, collections.Iterable):
imports = set()
@ -370,7 +371,7 @@ class MigrationWriter(object):
return format % (", ".join(strings)), imports
# Compiled regex
elif isinstance(value, COMPILED_REGEX_TYPE):
imports = set(["import re"])
imports = {"import re"}
regex_pattern, pattern_imports = cls.serialize(value.pattern)
regex_flags, flag_imports = cls.serialize(value.flags)
imports.update(pattern_imports)

View File

@ -54,9 +54,9 @@ def DO_NOTHING(collector, field, sub_objs, using):
class Collector(object):
def __init__(self, using):
self.using = using
# Initially, {model: set([instances])}, later values become lists.
# Initially, {model: {instances}}, later values become lists.
self.data = {}
self.field_updates = {} # {model: {(field, value): set([instances])}}
self.field_updates = {} # {model: {(field, value): {instances}}}
# fast_deletes is a list of queryset-likes that can be deleted without
# fetching the objects into memory.
self.fast_deletes = []
@ -66,7 +66,7 @@ class Collector(object):
# should be included, as the dependencies exist only between actual
# database tables; proxy models are represented here by their concrete
# parent.
self.dependencies = {} # {model: set([models])}
self.dependencies = {} # {model: {models}}
def add(self, objs, source=None, nullable=False, reverse_dependency=False):
"""

View File

@ -349,7 +349,7 @@ class Field(RegisterLookupMixin):
"validators": "_validators",
"verbose_name": "_verbose_name",
}
equals_comparison = set(["choices", "validators", "db_tablespace"])
equals_comparison = {"choices", "validators", "db_tablespace"}
for name, default in possibles.items():
value = getattr(self, attr_overrides.get(name, name))
# Unroll anything iterable for choices into a concrete list

View File

@ -8,12 +8,12 @@ import re
# Valid query types (a set is used for speedy lookups). These are (currently)
# considered SQL-specific; other storage systems may choose to use different
# lookup types.
QUERY_TERMS = set([
QUERY_TERMS = {
'exact', 'iexact', 'contains', 'icontains', 'gt', 'gte', 'lt', 'lte', 'in',
'startswith', 'istartswith', 'endswith', 'iendswith', 'range', 'year',
'month', 'day', 'week_day', 'hour', 'minute', 'second', 'isnull', 'search',
'regex', 'iregex',
])
}
# Size of each "chunk" for get_iterator calls.
# Larger values are slightly faster at the expense of more storage space.

View File

@ -574,7 +574,7 @@ class Query(object):
return
orig_opts = self.get_meta()
seen = {}
must_include = {orig_opts.concrete_model: set([orig_opts.pk])}
must_include = {orig_opts.concrete_model: {orig_opts.pk}}
for field_name in field_names:
parts = field_name.split(LOOKUP_SEP)
cur_model = self.model._meta.concrete_model
@ -2024,7 +2024,7 @@ def add_to_dict(data, key, value):
if key in data:
data[key].add(value)
else:
data[key] = set([value])
data[key] = {value}
def is_reverse_o2o(field):

View File

@ -298,7 +298,7 @@ def _non_atomic_requests(view, using):
try:
view._non_atomic_requests.add(using)
except AttributeError:
view._non_atomic_requests = set([using])
view._non_atomic_requests = {using}
return view

View File

@ -17,7 +17,7 @@ setting_changed = Signal(providing_args=["setting", "value", "enter"])
# except for cases where the receiver is related to a contrib app.
# Settings that may not work well when using 'override_settings' (#19031)
COMPLEX_OVERRIDE_SETTINGS = set(['DATABASES'])
COMPLEX_OVERRIDE_SETTINGS = {'DATABASES'}
@receiver(setting_changed)

View File

@ -225,8 +225,8 @@ def sanitize_separators(value):
# Special case where we suspect a dot meant decimal separator (see #22171)
pass
else:
for replacement in set([
thousand_sep, unicodedata.normalize('NFKD', thousand_sep)]):
for replacement in {
thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}:
value = value.replace(replacement, '')
parts.append(value)
value = '.'.join(reversed(parts))

View File

@ -310,7 +310,7 @@ Argument Value
``model`` ``Topping`` (the class of the objects added to the
``Pizza``)
``pk_set`` ``set([t.id])`` (since only ``Topping t`` was added to the relation)
``pk_set`` ``{t.id}`` (since only ``Topping t`` was added to the relation)
``using`` ``"default"`` (since the default router sends writes here)
============== ============================================================
@ -337,7 +337,7 @@ Argument Value
``model`` ``Pizza`` (the class of the objects removed from the
``Topping``)
``pk_set`` ``set([p.id])`` (since only ``Pizza p`` was removed from the
``pk_set`` ``{p.id}`` (since only ``Pizza p`` was removed from the
relation)
``using`` ``"default"`` (since the default router sends writes here)

View File

@ -91,11 +91,11 @@ class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter):
parameter_name = 'department'
def lookups(self, request, model_admin):
return sorted(set([
return sorted({
(employee.department.id, # Intentionally not a string (Refs #19318)
employee.department.code)
for employee in model_admin.get_queryset(request).all()
]))
})
def queryset(self, request, queryset):
if self.value():

View File

@ -429,7 +429,7 @@ class ModelTest(TestCase):
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
s = set([a10, a11, a12])
s = {a10, a11, a12}
self.assertTrue(Article.objects.get(headline='Article 11') in s)
def test_field_ordering(self):

16
tests/cache/tests.py vendored
View File

@ -1422,16 +1422,16 @@ class CacheUtils(TestCase):
def test_patch_cache_control(self):
tests = (
# Initial Cache-Control, kwargs to patch_cache_control, expected Cache-Control parts
(None, {'private': True}, set(['private'])),
(None, {'private': True}, {'private'}),
# Test whether private/public attributes are mutually exclusive
('private', {'private': True}, set(['private'])),
('private', {'public': True}, set(['public'])),
('public', {'public': True}, set(['public'])),
('public', {'private': True}, set(['private'])),
('must-revalidate,max-age=60,private', {'public': True}, set(['must-revalidate', 'max-age=60', 'public'])),
('must-revalidate,max-age=60,public', {'private': True}, set(['must-revalidate', 'max-age=60', 'private'])),
('must-revalidate,max-age=60', {'public': True}, set(['must-revalidate', 'max-age=60', 'public'])),
('private', {'private': True}, {'private'}),
('private', {'public': True}, {'public'}),
('public', {'public': True}, {'public'}),
('public', {'private': True}, {'private'}),
('must-revalidate,max-age=60,private', {'public': True}, {'must-revalidate', 'max-age=60', 'public'}),
('must-revalidate,max-age=60,public', {'private': True}, {'must-revalidate', 'max-age=60', 'private'}),
('must-revalidate,max-age=60', {'public': True}, {'must-revalidate', 'max-age=60', 'public'}),
)
cc_delim_re = re.compile(r'\s*,\s*')

View File

@ -281,9 +281,9 @@ class FileStorageTests(unittest.TestCase):
os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
dirs, files = self.storage.listdir('')
self.assertEqual(set(dirs), set(['storage_dir_1']))
self.assertEqual(set(dirs), {'storage_dir_1'})
self.assertEqual(set(files),
set(['storage_test_1', 'storage_test_2']))
{'storage_test_1', 'storage_test_2'})
self.storage.delete('storage_test_1')
self.storage.delete('storage_test_2')

View File

@ -55,7 +55,7 @@ class IntrospectionTests(TestCase):
def test_installed_models(self):
tables = [Article._meta.db_table, Reporter._meta.db_table]
models = connection.introspection.installed_models(tables)
self.assertEqual(models, set([Article, Reporter]))
self.assertEqual(models, {Article, Reporter})
def test_sequence_list(self):
sequences = connection.introspection.sequence_list()
@ -129,8 +129,8 @@ class IntrospectionTests(TestCase):
key_columns = connection.introspection.get_key_columns(cursor, Article._meta.db_table)
self.assertEqual(
set(key_columns),
set([('reporter_id', Reporter._meta.db_table, 'id'),
('response_to_id', Article._meta.db_table, 'id')]))
{('reporter_id', Reporter._meta.db_table, 'id'),
('response_to_id', Article._meta.db_table, 'id')})
def test_get_primary_key_column(self):
with connection.cursor() as cursor:

View File

@ -34,7 +34,7 @@ class ExistingRelatedInstancesTests(TestCase):
with self.assertNumQueries(1):
pools = tournament_1.pool_set.all() | tournament_2.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, set((tournament_1, tournament_2)))
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_or_different_cached_items(self):
tournament = Tournament.objects.get(pk=1)
@ -52,12 +52,12 @@ class ExistingRelatedInstancesTests(TestCase):
with self.assertNumQueries(2):
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=3)
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, set((tournament_1, tournament_2)))
self.assertEqual(related_objects, {tournament_1, tournament_2})
# and the other direction
with self.assertNumQueries(2):
pools = Pool.objects.filter(pk=3) | tournament_1.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, set((tournament_1, tournament_2)))
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_and(self):
tournament = Tournament.objects.get(pk=1)

View File

@ -114,7 +114,7 @@ class LookupTests(TestCase):
self.assertEqual(arts[self.a1.id], self.a1)
self.assertEqual(arts[self.a2.id], self.a2)
self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk(set([self.a3.id])), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3})
self.assertEqual(Article.objects.in_bulk([1000]), {})

View File

@ -73,9 +73,9 @@ class AutodetectorTests(TestCase):
book_with_field_and_author_renamed = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("writer", models.ForeignKey("testapp.Writer")), ("title", models.CharField(max_length=200))])
book_with_multiple_authors = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author")), ("title", models.CharField(max_length=200))])
book_with_multiple_authors_through_attribution = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("authors", models.ManyToManyField("testapp.Author", through="otherapp.Attribution")), ("title", models.CharField(max_length=200))])
book_unique = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("author", "title")])})
book_unique_2 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("title", "author")])})
book_unique_3 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": set([("title", "newfield")])})
book_unique = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": {("author", "title")}})
book_unique_2 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": {("title", "author")}})
book_unique_3 = ModelState("otherapp", "Book", [("id", models.AutoField(primary_key=True)), ("newfield", models.IntegerField()), ("author", models.ForeignKey("testapp.Author")), ("title", models.CharField(max_length=200))], {"unique_together": {("title", "newfield")}})
attribution = ModelState("otherapp", "Attribution", [("id", models.AutoField(primary_key=True)), ("author", models.ForeignKey("testapp.Author")), ("book", models.ForeignKey("otherapp.Book"))])
edition = ModelState("thirdapp", "Edition", [("id", models.AutoField(primary_key=True)), ("book", models.ForeignKey("otherapp.Book"))])
custom_user = ModelState("thirdapp", "CustomUser", [("id", models.AutoField(primary_key=True)), ("username", models.CharField(max_length=255))], bases=(AbstractBaseUser, ))
@ -85,7 +85,7 @@ class AutodetectorTests(TestCase):
aardvark_based_on_author = ModelState("testapp", "Aardvark", [], bases=("testapp.Author", ))
aardvark_pk_fk_author = ModelState("testapp", "Aardvark", [("id", models.OneToOneField("testapp.Author", primary_key=True))])
knight = ModelState("eggs", "Knight", [("id", models.AutoField(primary_key=True))])
rabbit = ModelState("eggs", "Rabbit", [("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight")), ("parent", models.ForeignKey("eggs.Rabbit"))], {"unique_together": set([("parent", "knight")])})
rabbit = ModelState("eggs", "Rabbit", [("id", models.AutoField(primary_key=True)), ("knight", models.ForeignKey("eggs.Knight")), ("parent", models.ForeignKey("eggs.Rabbit"))], {"unique_together": {("parent", "knight")}})
def repr_changes(self, changes):
output = ""
@ -187,7 +187,7 @@ class AutodetectorTests(TestCase):
graph = MigrationGraph()
changes = autodetector.arrange_for_graph(changes, graph)
changes["testapp"][0].dependencies.append(("otherapp", "0001_initial"))
changes = autodetector._trim_to_apps(changes, set(["testapp"]))
changes = autodetector._trim_to_apps(changes, {"testapp"})
# Make sure there's the right set of migrations
self.assertEqual(changes["testapp"][0].name, "0001_initial")
self.assertEqual(changes["otherapp"][0].name, "0001_initial")
@ -466,7 +466,7 @@ class AutodetectorTests(TestCase):
# Right dependencies?
self.assertEqual(changes['testapp'][0].dependencies, [("otherapp", "auto_1")])
self.assertEqual(changes['otherapp'][0].dependencies, [])
self.assertEqual(set(changes['otherapp'][1].dependencies), set([("otherapp", "auto_1"), ("testapp", "auto_1")]))
self.assertEqual(set(changes['otherapp'][1].dependencies), {("otherapp", "auto_1"), ("testapp", "auto_1")})
def test_same_app_circular_fk_dependency(self):
"""
@ -522,7 +522,7 @@ class AutodetectorTests(TestCase):
action = migration.operations[0]
self.assertEqual(action.__class__.__name__, "AlterUniqueTogether")
self.assertEqual(action.name, "book")
self.assertEqual(action.unique_together, set([("author", "title")]))
self.assertEqual(action.unique_together, {("author", "title")})
def test_unique_together_no_changes(self):
"Tests that unique_togther doesn't generate a migration if no changes have been made"
@ -594,7 +594,7 @@ class AutodetectorTests(TestCase):
action = migration.operations[0]
self.assertEqual(action.__class__.__name__, "AlterUniqueTogether")
self.assertEqual(action.name, "book")
self.assertEqual(action.unique_together, set([("title", "author")]))
self.assertEqual(action.unique_together, {("title", "author")})
def test_add_field_and_unique_together(self):
"Tests that added fields will be created before using them in unique together"
@ -612,12 +612,12 @@ class AutodetectorTests(TestCase):
action2 = migration.operations[1]
self.assertEqual(action1.__class__.__name__, "AddField")
self.assertEqual(action2.__class__.__name__, "AlterUniqueTogether")
self.assertEqual(action2.unique_together, set([("title", "newfield")]))
self.assertEqual(action2.unique_together, {("title", "newfield")})
def test_remove_index_together(self):
author_index_together = ModelState("testapp", "Author", [
("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200))
], {"index_together": set([("id", "name")])})
], {"index_together": {("id", "name")}})
before = self.make_project_state([author_index_together])
after = self.make_project_state([self.author_name])
@ -636,7 +636,7 @@ class AutodetectorTests(TestCase):
def test_remove_unique_together(self):
author_unique_together = ModelState("testapp", "Author", [
("id", models.AutoField(primary_key=True)), ("name", models.CharField(max_length=200))
], {"unique_together": set([("id", "name")])})
], {"unique_together": {("id", "name")}})
before = self.make_project_state([author_unique_together])
after = self.make_project_state([self.author_name])
@ -1267,7 +1267,7 @@ class AutodetectorTests(TestCase):
self.assertOperationTypes(changes, 'a', 1, ["AddField"])
self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
self.assertEqual(changes['a'][0].dependencies, [])
self.assertEqual(set(changes['a'][1].dependencies), set([('a', 'auto_1'), ('b', 'auto_1')]))
self.assertEqual(set(changes['a'][1].dependencies), {('a', 'auto_1'), ('b', 'auto_1')})
self.assertEqual(changes['b'][0].dependencies, [('__setting__', 'AUTH_USER_MODEL')])
@override_settings(AUTH_USER_MODEL="b.Tenant")
@ -1298,7 +1298,7 @@ class AutodetectorTests(TestCase):
self.assertOperationTypes(changes, 'a', 1, ["AddField"])
self.assertOperationTypes(changes, 'b', 0, ["CreateModel"])
self.assertEqual(changes['a'][0].dependencies, [])
self.assertEqual(set(changes['a'][1].dependencies), set([('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')]))
self.assertEqual(set(changes['a'][1].dependencies), {('__setting__', 'AUTH_USER_MODEL'), ('a', 'auto_1')})
self.assertEqual(changes['b'][0].dependencies, [('a', 'auto_1')])
@override_settings(AUTH_USER_MODEL="a.Person")

View File

@ -25,7 +25,7 @@ class RecorderTests(TestCase):
recorder.record_applied("myapp", "0432_ponies")
self.assertEqual(
set((x, y) for (x, y) in recorder.applied_migrations() if x == "myapp"),
set([("myapp", "0432_ponies")]),
{("myapp", "0432_ponies")},
)
# That should not affect records of another database
recorder_other = MigrationRecorder(connections['other'])

View File

@ -66,7 +66,7 @@ class StateTests(TestCase):
self.assertEqual(author_state.fields[1][1].max_length, 255)
self.assertEqual(author_state.fields[2][1].null, False)
self.assertEqual(author_state.fields[3][1].null, True)
self.assertEqual(author_state.options, {"unique_together": set([("name", "bio")]), "index_together": set([("bio", "age")])})
self.assertEqual(author_state.options, {"unique_together": {("name", "bio")}, "index_together": {("bio", "age")}})
self.assertEqual(author_state.bases, (models.Model, ))
self.assertEqual(book_state.app_label, "migrations")

View File

@ -78,7 +78,7 @@ class WriterTests(TestCase):
self.assertEqual(string, "'foobar'")
self.assertSerializedEqual({1: 2})
self.assertSerializedEqual(["a", 2, True, None])
self.assertSerializedEqual(set([2, 3, "eighty"]))
self.assertSerializedEqual({2, 3, "eighty"})
self.assertSerializedEqual({"lalalala": ["yeah", "no", "maybe"]})
self.assertSerializedEqual(_('Hello'))
# Builtins
@ -120,7 +120,7 @@ class WriterTests(TestCase):
SettingsReference("someapp.model", "AUTH_USER_MODEL"),
(
"settings.AUTH_USER_MODEL",
set(["from django.conf import settings"]),
{"from django.conf import settings"},
)
)
self.assertSerializedResultEqual(

View File

@ -719,9 +719,9 @@ class GenericRelationTests(TestCase):
# If we limit to books, we know that they will have 'read_by'
# attributes, so the following makes sense:
qs = TaggedItem.objects.filter(content_type=ct, tag='awesome').prefetch_related('content_object__read_by')
readers_of_awesome_books = set([r.name for tag in qs
for r in tag.content_object.read_by.all()])
self.assertEqual(readers_of_awesome_books, set(["me", "you", "someone"]))
readers_of_awesome_books = {r.name for tag in qs
for r in tag.content_object.read_by.all()}
self.assertEqual(readers_of_awesome_books, {"me", "you", "someone"})
def test_nullable_GFK(self):
TaggedItem.objects.create(tag="awesome", content_object=self.book1,

View File

@ -91,10 +91,10 @@ class Queries1Tests(BaseQuerysetTest):
qs1 = Tag.objects.filter(pk__lte=0)
qs2 = Tag.objects.filter(parent__in=qs1)
qs3 = Tag.objects.filter(parent__in=qs2)
self.assertEqual(qs3.query.subq_aliases, set(['T', 'U', 'V']))
self.assertEqual(qs3.query.subq_aliases, {'T', 'U', 'V'})
self.assertIn('v0', str(qs3.query).lower())
qs4 = qs3.filter(parent__in=qs1)
self.assertEqual(qs4.query.subq_aliases, set(['T', 'U', 'V']))
self.assertEqual(qs4.query.subq_aliases, {'T', 'U', 'V'})
# It is possible to reuse U for the second subquery, no need to use W.
self.assertNotIn('w0', str(qs4.query).lower())
# So, 'U0."id"' is referenced twice.
@ -1972,29 +1972,29 @@ class SubqueryTests(TestCase):
def test_ordered_subselect(self):
"Subselects honor any manual ordering"
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3, 4]))
self.assertEqual(set(query.values_list('id', flat=True)), {3, 4})
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3, 4]))
self.assertEqual(set(query.values_list('id', flat=True)), {3, 4})
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3]))
self.assertEqual(set(query.values_list('id', flat=True)), {3})
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])
self.assertEqual(set(query.values_list('id', flat=True)), set([1, 2]))
self.assertEqual(set(query.values_list('id', flat=True)), {1, 2})
def test_slice_subquery_and_query(self):
"""
Slice a query that has a sliced subquery
"""
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2]
self.assertEqual(set([x.id for x in query]), set([3, 4]))
self.assertEqual({x.id for x in query}, {3, 4})
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3]
self.assertEqual(set([x.id for x in query]), set([3]))
self.assertEqual({x.id for x in query}, {3})
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])[1:]
self.assertEqual(set([x.id for x in query]), set([2]))
self.assertEqual({x.id for x in query}, {2})
def test_related_sliced_subquery(self):
"""
@ -2010,18 +2010,18 @@ class SubqueryTests(TestCase):
query = ManagedModel.normal_manager.filter(
tag__in=Tag.objects.order_by('-id')[:1]
)
self.assertEqual(set([x.id for x in query]), set([mm2.id]))
self.assertEqual({x.id for x in query}, {mm2.id})
def test_sliced_delete(self):
"Delete queries can safely contain sliced subqueries"
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1, 2, 3]))
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 2, 3})
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1, 3]))
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {1, 3})
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([3]))
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), {3})
class CloneTests(TestCase):
@ -2360,7 +2360,7 @@ class ToFieldTests(TestCase):
self.assertEqual(
set(Eaten.objects.filter(food__in=[apple, pear])),
set([lunch, dinner]),
{lunch, dinner},
)
def test_reverse_in(self):
@ -2371,7 +2371,7 @@ class ToFieldTests(TestCase):
self.assertEqual(
set(Food.objects.filter(eaten__in=[lunch_apple, lunch_pear])),
set([apple, pear])
{apple, pear}
)
def test_single_object(self):
@ -2381,7 +2381,7 @@ class ToFieldTests(TestCase):
self.assertEqual(
set(Eaten.objects.filter(food=apple)),
set([lunch, dinner])
{lunch, dinner}
)
def test_single_object_reverse(self):
@ -2390,7 +2390,7 @@ class ToFieldTests(TestCase):
self.assertEqual(
set(Food.objects.filter(eaten=lunch)),
set([apple])
{apple}
)
def test_recursive_fk(self):

View File

@ -68,7 +68,7 @@ class RequestsTests(SimpleTestCase):
self.assertEqual(list(request.GET.keys()), [])
self.assertEqual(list(request.POST.keys()), [])
self.assertEqual(list(request.COOKIES.keys()), [])
self.assertEqual(set(request.META.keys()), set(['PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input']))
self.assertEqual(set(request.META.keys()), {'PATH_INFO', 'REQUEST_METHOD', 'SCRIPT_NAME', 'wsgi.input'})
self.assertEqual(request.META['PATH_INFO'], 'bogus')
self.assertEqual(request.META['REQUEST_METHOD'], 'bogus')
self.assertEqual(request.META['SCRIPT_NAME'], '')

View File

@ -993,8 +993,8 @@ class ContextTests(TestCase):
l = ContextList([c1, c2])
# None, True and False are builtins of BaseContext, and present
# in every Context without needing to be added.
self.assertEqual(set(['None', 'True', 'False', 'hello', 'goodbye',
'python', 'dolly']),
self.assertEqual({'None', 'True', 'False', 'hello', 'goodbye',
'python', 'dolly'},
l.keys())
def test_15368(self):

View File

@ -266,7 +266,7 @@ class SimpleLazyObjectTestCase(LazyObjectTestCase):
def test_list_set(self):
lazy_list = SimpleLazyObject(lambda: [1, 2, 3, 4, 5])
lazy_set = SimpleLazyObject(lambda: set([1, 2, 3, 4]))
lazy_set = SimpleLazyObject(lambda: {1, 2, 3, 4})
self.assertTrue(1 in lazy_list)
self.assertTrue(1 in lazy_set)
self.assertFalse(6 in lazy_list)