1
0
mirror of https://github.com/django/django.git synced 2024-12-22 09:05:43 +00:00

Fixed #21287 -- Fixed E123 pep8 warnings

This commit is contained in:
Alasdair Nicol 2013-10-18 10:02:43 +01:00
parent 65750b8352
commit a800036981
71 changed files with 152 additions and 152 deletions

View File

@ -242,7 +242,7 @@ class BooleanFieldListFilter(FieldListFilter):
'selected': self.lookup_val == lookup and not self.lookup_val2,
'query_string': cl.get_query_string({
self.lookup_kwarg: lookup,
}, [self.lookup_kwarg2]),
}, [self.lookup_kwarg2]),
'display': title,
}
if isinstance(self.field, models.NullBooleanField):
@ -250,7 +250,7 @@ class BooleanFieldListFilter(FieldListFilter):
'selected': self.lookup_val2 == 'True',
'query_string': cl.get_query_string({
self.lookup_kwarg2: 'True',
}, [self.lookup_kwarg]),
}, [self.lookup_kwarg]),
'display': _('Unknown'),
}

View File

@ -1200,7 +1200,7 @@ class ModelAdmin(BaseModelAdmin):
'The %(name)s "%(obj)s" was deleted successfully.') % {
'name': force_text(opts.verbose_name),
'obj': force_text(obj_display)
}, messages.SUCCESS)
}, messages.SUCCESS)
if self.has_change_permission(request, None):
post_url = reverse('admin:%s_%s_changelist' %

View File

@ -35,7 +35,7 @@ class Command(BaseCommand):
try:
u = UserModel._default_manager.using(options.get('database')).get(**{
UserModel.USERNAME_FIELD: username
})
})
except UserModel.DoesNotExist:
raise CommandError("user '%s' does not exist" % username)

View File

@ -32,7 +32,7 @@ class UserCreationFormTest(TestCase):
'username': 'testclient',
'password1': 'test123',
'password2': 'test123',
}
}
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["username"].errors,
@ -43,7 +43,7 @@ class UserCreationFormTest(TestCase):
'username': 'jsmith!',
'password1': 'test123',
'password2': 'test123',
}
}
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["username"].errors,
@ -55,7 +55,7 @@ class UserCreationFormTest(TestCase):
'username': 'jsmith',
'password1': 'test123',
'password2': 'test',
}
}
form = UserCreationForm(data)
self.assertFalse(form.is_valid())
self.assertEqual(form["password2"].errors,
@ -82,7 +82,7 @@ class UserCreationFormTest(TestCase):
'username': 'jsmith@example.com',
'password1': 'test123',
'password2': 'test123',
}
}
form = UserCreationForm(data)
self.assertTrue(form.is_valid())
u = form.save()
@ -101,7 +101,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'jsmith_does_not_exist',
'password': 'test123',
}
}
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
@ -114,7 +114,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'inactive',
'password': 'password',
}
}
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
@ -126,7 +126,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'inactive',
'password': 'password',
}
}
form = AuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(),
@ -137,7 +137,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'inactive',
'password': 'password',
}
}
class AuthenticationFormWithInactiveUsersOkay(AuthenticationForm):
def confirm_login_allowed(self, user):
@ -161,7 +161,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'testclient',
'password': 'password',
}
}
form = PickyAuthenticationForm(None, data)
self.assertFalse(form.is_valid())
self.assertEqual(form.non_field_errors(), ["Sorry, nobody's allowed in."])
@ -171,7 +171,7 @@ class AuthenticationFormTest(TestCase):
data = {
'username': 'testclient',
'password': 'password',
}
}
form = AuthenticationForm(None, data)
self.assertTrue(form.is_valid())
self.assertEqual(form.non_field_errors(), [])
@ -215,7 +215,7 @@ class SetPasswordFormTest(TestCase):
data = {
'new_password1': 'abc123',
'new_password2': 'abc',
}
}
form = SetPasswordForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors,
@ -226,7 +226,7 @@ class SetPasswordFormTest(TestCase):
data = {
'new_password1': 'abc123',
'new_password2': 'abc123',
}
}
form = SetPasswordForm(user, data)
self.assertTrue(form.is_valid())
@ -243,7 +243,7 @@ class PasswordChangeFormTest(TestCase):
'old_password': 'test',
'new_password1': 'abc123',
'new_password2': 'abc123',
}
}
form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["old_password"].errors,
@ -256,7 +256,7 @@ class PasswordChangeFormTest(TestCase):
'old_password': 'password',
'new_password1': 'abc123',
'new_password2': 'abc',
}
}
form = PasswordChangeForm(user, data)
self.assertFalse(form.is_valid())
self.assertEqual(form["new_password2"].errors,
@ -269,7 +269,7 @@ class PasswordChangeFormTest(TestCase):
'old_password': 'password',
'new_password1': 'abc123',
'new_password2': 'abc123',
}
}
form = PasswordChangeForm(user, data)
self.assertTrue(form.is_valid())

View File

@ -49,7 +49,7 @@ class AuthViewsTestCase(TestCase):
response = self.client.post('/login/', {
'username': 'testclient',
'password': password,
})
})
self.assertTrue(SESSION_KEY in self.client.session)
return response
@ -180,7 +180,7 @@ class PasswordResetTest(AuthViewsTestCase):
response = self.client.post('/password_reset/',
{'email': 'staffmember@example.com'},
HTTP_HOST='www.example:dr.frankenstein@evil.tld'
)
)
self.assertEqual(response.status_code, 400)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(len(logger_calls), 1)
@ -193,7 +193,7 @@ class PasswordResetTest(AuthViewsTestCase):
response = self.client.post('/admin_password_reset/',
{'email': 'staffmember@example.com'},
HTTP_HOST='www.example:dr.frankenstein@evil.tld'
)
)
self.assertEqual(response.status_code, 400)
self.assertEqual(len(mail.outbox), 0)
self.assertEqual(len(logger_calls), 1)
@ -357,7 +357,7 @@ class ChangePasswordTest(AuthViewsTestCase):
})
self.assertFormError(response, AuthenticationForm.error_messages['invalid_login'] % {
'username': User._meta.get_field('username').verbose_name
})
})
def logout(self):
self.client.get('/logout/')

View File

@ -354,7 +354,7 @@ def create_generic_related_manager(superclass):
'%s__pk' % self.content_type_field_name: self.content_type.id,
'%s__in' % self.object_id_field_name:
set(obj._get_pk_val() for obj in instances)
}
}
qs = super(GenericRelatedObjectManager, self).get_queryset().using(db).filter(**query)
# We (possibly) need to convert object IDs to the type of the
# instances' PK in order to match up instances:

View File

@ -32,7 +32,7 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context())
).render(Context())
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
def test_get_flatpages_tag_for_anon_user(self):
@ -43,9 +43,9 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context({
).render(Context({
'anonuser': AnonymousUser()
}))
}))
self.assertEqual(out, "A Flatpage,A Nested Flatpage,")
@skipIfCustomUser
@ -58,9 +58,9 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context({
).render(Context({
'me': me
}))
}))
self.assertEqual(out, "A Flatpage,A Nested Flatpage,Sekrit Nested Flatpage,Sekrit Flatpage,")
def test_get_flatpages_with_prefix(self):
@ -71,7 +71,7 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in location_flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context())
).render(Context())
self.assertEqual(out, "A Nested Flatpage,")
def test_get_flatpages_with_prefix_for_anon_user(self):
@ -82,9 +82,9 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in location_flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context({
).render(Context({
'anonuser': AnonymousUser()
}))
}))
self.assertEqual(out, "A Nested Flatpage,")
@skipIfCustomUser
@ -97,9 +97,9 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in location_flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context({
).render(Context({
'me': me
}))
}))
self.assertEqual(out, "A Nested Flatpage,Sekrit Nested Flatpage,")
def test_get_flatpages_with_variable_prefix(self):
@ -110,9 +110,9 @@ class FlatpageTemplateTagTests(TestCase):
"{% for page in location_flatpages %}"
"{{ page.title }},"
"{% endfor %}"
).render(Context({
).render(Context({
'location_prefix': '/location/'
}))
}))
self.assertEqual(out, "A Nested Flatpage,")
def test_parsing_errors(self):

View File

@ -114,7 +114,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
'distance_lt' : (SDODistance('<'), dtypes),
'distance_lte' : (SDODistance('<='), dtypes),
'dwithin' : (SDODWithin(), dtypes),
}
}
geometry_functions = {
'contains' : SDOOperation('SDO_CONTAINS'),
@ -129,7 +129,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations):
'relate' : (SDORelate, six.string_types), # Oracle uses a different syntax, e.g., 'mask=inside+touch'
'touches' : SDOOperation('SDO_TOUCH'),
'within' : SDOOperation('SDO_INSIDE'),
}
}
geometry_functions.update(distance_functions)
gis_terms = set(['isnull'])

View File

@ -119,7 +119,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
# The "&&" operator returns true if A's bounding box overlaps
# B's bounding box.
'bboverlaps' : PostGISOperator('&&'),
}
}
self.geometry_functions = {
'equals' : PostGISFunction(prefix, 'Equals'),
@ -256,7 +256,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations):
'GeoDjango requires at least PostGIS version 1.3. '
'Was the database created from a spatial database '
'template?' % self.connection.settings_dict['NAME']
)
)
version = vtup[1:]
return version

View File

@ -103,14 +103,14 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations):
# These are implemented here as synonyms for Equals
'same_as' : SpatiaLiteFunction('Equals'),
'exact' : SpatiaLiteFunction('Equals'),
}
}
distance_functions = {
'distance_gt' : (get_dist_ops('>'), dtypes),
'distance_gte' : (get_dist_ops('>='), dtypes),
'distance_lt' : (get_dist_ops('<'), dtypes),
'distance_lte' : (get_dist_ops('<='), dtypes),
}
}
geometry_functions.update(distance_functions)
def __init__(self, connection):

View File

@ -24,7 +24,7 @@ class GeometryField(forms.Field):
'invalid_geom_type' : _('Invalid geometry type.'),
'transform_error' : _('An error occurred when transforming the geometry '
'to the SRID of the geometry form field.'),
}
}
def __init__(self, **kwargs):
# Pop out attributes from the database field, or use sensible

View File

@ -67,7 +67,7 @@ class Command(LabelCommand):
'determined, the SRID of the data source is used.'),
make_option('--mapping', action='store_true', dest='mapping',
help='Generate mapping dictionary for use with `LayerMapping`.')
)
)
requires_model_validation = False

View File

@ -252,7 +252,7 @@ class Distance(MeasureBase):
'survey_ft' : 0.304800609601,
'um' : 0.000001,
'yd': 0.9144,
}
}
# Unit aliases for `UNIT` terms encountered in Spatial Reference WKT.
ALIAS = {
@ -292,7 +292,7 @@ class Distance(MeasureBase):
'U.S. Foot' : 'survey_ft',
'Yard (Indian)' : 'indian_yd',
'Yard (Sears)' : 'sears_yd'
}
}
LALIAS = dict((k.lower(), v) for k, v in ALIAS.items())
def __mul__(self, other):
@ -305,7 +305,7 @@ class Distance(MeasureBase):
else:
raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % {
"distance" : pretty_name(self.__class__),
})
})
class Area(MeasureBase):

View File

@ -51,7 +51,7 @@ interstate_data = (
15.544, 14.975, 15.688, 16.099, 15.197, 17.268, 19.857,
15.435),
),
)
)
# Bounding box polygon for inner-loop of Houston (in projected coordinate
# system 32140), with elevation values from the National Elevation Dataset

View File

@ -28,7 +28,7 @@ class GeoAdminTest(TestCase):
def test_olmap_OSM_rendering(self):
geoadmin = admin.site._registry[City]
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""",
result)
@ -36,7 +36,7 @@ class GeoAdminTest(TestCase):
def test_olmap_WMS_rendering(self):
geoadmin = admin.GeoModelAdmin(City, admin.site)
result = geoadmin.get_map_widget(City._meta.get_field('point'))(
).render('point', Point(-79.460734, 40.18476))
).render('point', Point(-79.460734, 40.18476))
self.assertIn(
"""geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: \'basic\', format: 'image/jpeg'});""",
result)

View File

@ -66,7 +66,7 @@ class LayerMapping(object):
models.BigIntegerField : (OFTInteger, OFTReal, OFTString),
models.SmallIntegerField : (OFTInteger, OFTReal, OFTString),
models.PositiveSmallIntegerField : (OFTInteger, OFTReal, OFTString),
}
}
def __init__(self, model, data, mapping, layer=0,
source_srs=None, encoding='utf-8',

View File

@ -359,7 +359,7 @@ class BaseTests(object):
constants.WARNING: '',
constants.ERROR: 'bad',
29: 'custom',
}
}
)
def test_custom_tags(self):
storage = self.get_storage()

View File

@ -144,7 +144,7 @@ class Command(BaseCommand):
'object_name': obj.object._meta.object_name,
'pk': obj.object.pk,
'error_msg': force_text(e)
},)
},)
raise
self.loaded_object_count += loaded_objects_in_fixture

View File

@ -51,7 +51,7 @@ class TemplateCommand(BaseCommand):
help='The file name(s) to render. '
'Separate multiple extensions with commas, or use '
'-n multiple times.')
)
)
requires_model_validation = False
# Can't import settings during this command, because they haven't
# necessarily been created.

View File

@ -82,7 +82,7 @@ class DatabaseErrorWrapper(object):
DatabaseError,
InterfaceError,
Error,
):
):
db_exc_type = getattr(self.wrapper.Database, dj_exc_type.__name__)
if issubclass(exc_type, db_exc_type):
dj_exc_value = dj_exc_type(*exc_value.args)

View File

@ -147,7 +147,7 @@ class BaseFormSet(object):
'auto_id': self.auto_id,
'prefix': self.add_prefix(i),
'error_class': self.error_class,
}
}
if self.is_bound:
defaults['data'] = self.data
defaults['files'] = self.files

View File

@ -688,7 +688,7 @@ class BaseModelFormSet(BaseFormSet):
return ugettext("Please correct the duplicate data for %(field)s, "
"which must be unique.") % {
"field": get_text_list(unique_check, six.text_type(_("and"))),
}
}
def get_date_error_message(self, date_check):
return ugettext("Please correct the duplicate data for %(field_name)s "

View File

@ -526,9 +526,9 @@ def validate_host(host, allowed_hosts):
pattern == '*' or
pattern.startswith('.') and (
host.endswith(pattern) or host == pattern[1:]
) or
) or
pattern == host
)
)
if match:
return True

View File

@ -495,7 +495,7 @@ constant_string = r"""
'strsq': r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string
'i18n_open': re.escape("_("),
'i18n_close': re.escape(")"),
}
}
constant_string = constant_string.replace("\n", "")
filter_raw_string = r"""

View File

@ -190,7 +190,7 @@ class Parser(HTMLParser):
if name == "class"
else (name, value)
for name, value in attrs
]
]
element = Element(tag, attrs)
self.current.append(element)
if tag not in self.SELF_CLOSING_TAGS:

View File

@ -25,7 +25,7 @@ class DiscoverRunner(object):
make_option('-p', '--pattern', action='store', dest='pattern',
default="test*.py",
help='The test matching pattern. Defaults to test*.py.'),
)
)
def __init__(self, pattern=None, top_level=None,
verbosity=1, interactive=True, failfast=False,

View File

@ -72,7 +72,7 @@ def get_random_string(length=12,
random.getstate(),
time.time(),
settings.SECRET_KEY)).encode('utf-8')
).digest())
).digest())
return ''.join(random.choice(allowed_chars) for i in range(length))

View File

@ -136,7 +136,7 @@ class JsLexer(Lexer):
Tok("punct", literals("{ } ( [ . ; , < > + - * % & | ^ ! ~ ? : ="), next='reg'),
Tok("string", r'"([^"\\]|(\\(.|\n)))*?"', next='div'),
Tok("string", r"'([^'\\]|(\\(.|\n)))*?'", next='div'),
]
]
both_after = [
Tok("other", r"."),
@ -175,7 +175,7 @@ class JsLexer(Lexer):
[a-zA-Z0-9]* # trailing flags
""", next='div'),
] + both_after,
}
}
def __init__(self):
super(JsLexer, self).__init__(self.states, 'reg')

View File

@ -77,11 +77,11 @@
TEMPLATE_EXTENSIONS = [
".html",
".htm",
]
]
PYTHON_SOURCE_EXTENSIONS = [
".py",
]
]
TEMPLATE_ENCODING = "UTF-8"

View File

@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
[flake8]
exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py
ignore=E123,E124,E125,E126,E127,E128,E225,E226,E241,E251,E302,E501,E203,E221,E227,E231,E261,E301,F401,F403,F841,W601
ignore=E124,E125,E126,E127,E128,E225,E226,E241,E251,E302,E501,E203,E221,E227,E231,E261,E301,F401,F403,F841,W601
[metadata]
license-file = LICENSE

View File

@ -8,4 +8,4 @@ class Command(BaseCommand):
make_option('--extra',
action='store', dest='extra',
help='An arbitrary extra value passed to the context'),
)
)

View File

@ -171,7 +171,7 @@ class Fabric(models.Model):
('Textured', (
('x', 'Horizontal'),
('y', 'Vertical'),
)
)
),
('plain', 'Smooth'),
)

View File

@ -431,7 +431,7 @@ class AdminViewBasicTest(AdminViewBasicTestCase):
values=[p.name for p in Promo.objects.all()],
test=lambda obj, value:
obj.chap.book.promo_set.filter(name=value).exists()),
}
}
for filter_path, params in filters.items():
for value in params['values']:
query_string = urlencode({filter_path: value})
@ -1256,7 +1256,7 @@ class AdminViewPermissionsTest(TestCase):
'index': 0,
'action': ['delete_selected'],
'_selected_action': ['1'],
})
})
self.assertTemplateUsed(response, 'custom_admin/delete_selected_confirmation.html')
response = self.client.get('/test_admin/admin/admin_views/customarticle/%d/history/' % article_pk)
self.assertTemplateUsed(response, 'custom_admin/object_history.html')
@ -1474,7 +1474,7 @@ class AdminViewDeletedObjectsTest(TestCase):
"""<li>Super villain: <a href="/test_admin/admin/admin_views/supervillain/3/">Bob</a>""",
"""<li>Secret hideout: floating castle""",
"""<li>Super secret hideout: super floating castle!"""
]
]
response = self.client.get('/test_admin/admin/admin_views/villain/%s/delete/' % quote(3))
for should in should_contain:
self.assertContains(response, should, 1)

View File

@ -256,7 +256,7 @@ class AggregationTests(TestCase):
self.assertEqual(
Book.objects.annotate(c=Count('authors')).values('c').aggregate(Max('c')),
{'c__max': 3}
)
)
def test_field_error(self):
# Bad field requests in aggregates are caught and reported

View File

@ -607,7 +607,7 @@ class ModelTest(TestCase):
dicts = Article.objects.filter(
pub_date__year=2008).extra(
select={'dashed-value': '1'}
).values('headline', 'dashed-value')
).values('headline', 'dashed-value')
self.assertEqual([sorted(d.items()) for d in dicts],
[[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]])

View File

@ -150,7 +150,7 @@ class DummyCacheTests(unittest.TestCase):
'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
'ascii2': {'x' : 1}
}
}
for (key, value) in stuff.items():
self.cache.set(key, value)
self.assertEqual(self.cache.get(key), None)
@ -354,7 +354,7 @@ class BaseCacheTests(object):
'unicode_ascii': 'Iñtërnâtiônàlizætiøn1',
'Iñtërnâtiônàlizætiøn': 'Iñtërnâtiônàlizætiøn2',
'ascii2': {'x' : 1}
}
}
# Test `set`
for (key, value) in stuff.items():
self.cache.set(key, value)

View File

@ -61,7 +61,7 @@ class FileUploadTests(TestCase):
'name': 'Ringo',
'file_field1': file1,
'file_field2': file2,
}
}
for key in list(post_data):
try:
@ -112,7 +112,7 @@ class FileUploadTests(TestCase):
post_data = {
'file_unicode': file1,
}
}
response = self.client.post('/file_uploads/unicode_name/', post_data)

View File

@ -390,7 +390,7 @@ class TestFixtures(TestCase):
stdout.getvalue(),
"""[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
% widget.pk
)
)
def test_loaddata_works_when_fixture_has_forward_refs(self):
"""
@ -535,7 +535,7 @@ class NaturalKeyFixtureTests(TestCase):
'loaddata',
'forward_ref_lookup.json',
verbosity=0,
)
)
stdout = StringIO()
management.call_command(

View File

@ -1142,7 +1142,7 @@ class FieldsTests(SimpleTestCase):
('/django/forms/util.py', 'util.py'),
('/django/forms/utils.py', 'utils.py'),
('/django/forms/widgets.py', 'widgets.py')
]
]
for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0]))
@ -1163,7 +1163,7 @@ class FieldsTests(SimpleTestCase):
('/django/forms/util.py', 'util.py'),
('/django/forms/utils.py', 'utils.py'),
('/django/forms/widgets.py', 'widgets.py')
]
]
for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0]))
@ -1184,7 +1184,7 @@ class FieldsTests(SimpleTestCase):
('/django/forms/util.py', 'util.py'),
('/django/forms/utils.py', 'utils.py'),
('/django/forms/widgets.py', 'widgets.py')
]
]
for exp, got in zip(expected, fix_os_paths(f.choices)):
self.assertEqual(exp[1], got[1])
self.assertTrue(got[0].endswith(exp[0]))

View File

@ -996,9 +996,9 @@ class FormsFormsetTestCase(TestCase):
'choices-2-votes': '2',
'choices-3-choice': 'Three',
'choices-3-votes': '3',
},
},
prefix='choices',
)
)
# But we still only instantiate 3 forms
self.assertEqual(len(formset.forms), 3)
# and the formset isn't valid
@ -1028,9 +1028,9 @@ class FormsFormsetTestCase(TestCase):
'choices-2-votes': '2',
'choices-3-choice': 'Three',
'choices-3-votes': '3',
},
},
prefix='choices',
)
)
# Four forms are instantiated and no exception is raised
self.assertEqual(len(formset.forms), 4)
finally:

View File

@ -128,7 +128,7 @@ class ModelFormCallableModelDefault(TestCase):
'choice_int': obj2,
'multi_choice': [obj2,obj3],
'multi_choice_int': ChoiceOptionModel.objects.exclude(name="default"),
}).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
}).as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
<option value="1">ChoiceOption 1</option>
<option value="2" selected="selected">ChoiceOption 2</option>
<option value="3">ChoiceOption 3</option>

View File

@ -105,7 +105,7 @@ class GenericRelationsTests(TestCase):
('salty', Vegetable, bacon.pk),
('shiny', Animal, platypus.pk),
('yellow', Animal, lion.pk)
],
],
comp_func
)
lion.delete()
@ -115,7 +115,7 @@ class GenericRelationsTests(TestCase):
('fatty', Vegetable, bacon.pk),
('salty', Vegetable, bacon.pk),
('shiny', Animal, platypus.pk)
],
],
comp_func
)
@ -129,7 +129,7 @@ class GenericRelationsTests(TestCase):
('fatty', Vegetable, bacon.pk),
('salty', Vegetable, bacon.pk),
('shiny', Animal, platypus.pk)
],
],
comp_func
)
# If you delete a tag, the objects using the tag are unaffected
@ -142,7 +142,7 @@ class GenericRelationsTests(TestCase):
('fatty', Animal, platypus.pk),
('salty', Vegetable, bacon.pk),
('shiny', Animal, platypus.pk)
],
],
comp_func
)
TaggedItem.objects.filter(tag='fatty').delete()

View File

@ -787,7 +787,7 @@ class FormattingTests(TransRealMixin, TestCase):
'date_added': datetime.datetime(2009, 12, 31, 6, 0, 0),
'cents_paid': decimal.Decimal('59.47'),
'products_delivered': 12000,
})
})
context = Context({'form': form})
self.assertTrue(form.is_valid())

View File

@ -161,7 +161,7 @@ class AdminEmailHandlerTest(TestCase):
admin_email_handler = [
h for h in logger.handlers
if h.__class__.__name__ == "AdminEmailHandler"
][0]
][0]
return admin_email_handler
def test_fail_silently(self):
@ -171,7 +171,7 @@ class AdminEmailHandlerTest(TestCase):
@override_settings(
ADMINS=(('whatever admin', 'admin@example.com'),),
EMAIL_SUBJECT_PREFIX='-SuperAwesomeSubject-'
)
)
def test_accepts_args(self):
"""
Ensure that user-supplied arguments and the EMAIL_SUBJECT_PREFIX
@ -202,7 +202,7 @@ class AdminEmailHandlerTest(TestCase):
ADMINS=(('whatever admin', 'admin@example.com'),),
EMAIL_SUBJECT_PREFIX='-SuperAwesomeSubject-',
INTERNAL_IPS=('127.0.0.1',),
)
)
def test_accepts_args_and_request(self):
"""
Ensure that the subject is also handled if being
@ -237,7 +237,7 @@ class AdminEmailHandlerTest(TestCase):
ADMINS=(('admin', 'admin@example.com'),),
EMAIL_SUBJECT_PREFIX='',
DEBUG=False,
)
)
def test_subject_accepts_newlines(self):
"""
Ensure that newlines in email reports' subjects are escaped to avoid
@ -260,7 +260,7 @@ class AdminEmailHandlerTest(TestCase):
ADMINS=(('admin', 'admin@example.com'),),
EMAIL_SUBJECT_PREFIX='',
DEBUG=False,
)
)
def test_truncate_subject(self):
"""
RFC 2822's hard limit is 998 characters per line.
@ -281,7 +281,7 @@ class AdminEmailHandlerTest(TestCase):
@override_settings(
ADMINS=(('admin', 'admin@example.com'),),
DEBUG=False,
)
)
def test_uses_custom_email_backend(self):
"""
Refs #19325

View File

@ -326,7 +326,7 @@ class MailTests(HeadersCheckMixin, SimpleTestCase):
send_mass_mail([
('Subject1', 'Content1', 'from1@example.com', ['to1@example.com']),
('Subject2', 'Content2', 'from2@example.com', ['to2@example.com']),
], connection=connection)
], connection=connection)
self.assertEqual(mail.outbox, [])
self.assertEqual(len(connection.test_outbox), 2)
self.assertEqual(connection.test_outbox[0].subject, 'Subject1')

View File

@ -59,12 +59,12 @@ class ManagersRegressionTests(TestCase):
"<Child4: d2>",
"<Child4: f1>",
"<Child4: f2>"
]
]
)
self.assertQuerysetEqual(Child4.manager1.all(), [
"<Child4: d1>",
"<Child4: f1>"
],
],
ordered=False
)
self.assertQuerysetEqual(Child5._default_manager.all(), ["<Child5: fred>"])
@ -72,7 +72,7 @@ class ManagersRegressionTests(TestCase):
self.assertQuerysetEqual(Child7._default_manager.order_by('name'), [
"<Child7: barney>",
"<Child7: fred>"
]
]
)
def test_abstract_manager(self):

View File

@ -375,7 +375,7 @@ class MiddlewareTests(BaseMiddlewareExceptionTest):
self._add_middleware(pre_middleware)
self.assert_exceptions_handled('/middleware_exceptions/null_view/', [
"The view middleware_exceptions.views.null_view didn't return an HttpResponse object.",
],
],
ValueError())
# Check that the right middleware methods have been invoked
@ -392,7 +392,7 @@ class MiddlewareTests(BaseMiddlewareExceptionTest):
self._add_middleware(pre_middleware)
self.assert_exceptions_handled('/middleware_exceptions/null_view/', [
"The view middleware_exceptions.views.null_view didn't return an HttpResponse object."
],
],
ValueError())
# Check that the right middleware methods have been invoked
@ -687,7 +687,7 @@ class BadMiddlewareTests(BaseMiddlewareExceptionTest):
self.assert_exceptions_handled('/middleware_exceptions/null_view/', [
"The view middleware_exceptions.views.null_view didn't return an HttpResponse object.",
'Test Response Exception'
])
])
# Check that the right middleware methods have been invoked
self.assert_middleware_usage(pre_middleware, True, True, False, False, False)
@ -703,7 +703,7 @@ class BadMiddlewareTests(BaseMiddlewareExceptionTest):
self._add_middleware(pre_middleware)
self.assert_exceptions_handled('/middleware_exceptions/null_view/', [
"The view middleware_exceptions.views.null_view didn't return an HttpResponse object."
],
],
ValueError())
# Check that the right middleware methods have been invoked

View File

@ -33,12 +33,12 @@ class Whiz(models.Model):
('Group 1', (
(1, 'First'),
(2, 'Second'),
)
)
),
('Group 2', (
(3, 'Third'),
(4, 'Fourth'),
)
)
),
(0, 'Other'),
)

View File

@ -466,7 +466,7 @@ class ModelFormBaseTest(TestCase):
"""<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
<tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr>"""
)
)
def test_orderfields_form(self):
class OrderFields(forms.ModelForm):
@ -480,7 +480,7 @@ class ModelFormBaseTest(TestCase):
str(OrderFields()),
"""<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>"""
)
)
def test_orderfields2_form(self):
class OrderFields2(forms.ModelForm):
@ -831,13 +831,13 @@ class OldFormForXTests(TestCase):
"""<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>"""
)
)
self.assertHTMLEqual(
str(f.as_ul()),
"""<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li>
<li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" /></li>
<li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li>"""
)
)
self.assertHTMLEqual(
str(f["name"]),
"""<input id="id_name" type="text" name="name" maxlength="20" />""")
@ -849,7 +849,7 @@ class OldFormForXTests(TestCase):
"""<li>Name: <input type="text" name="name" maxlength="20" /></li>
<li>Slug: <input type="text" name="slug" maxlength="20" /></li>
<li>The URL: <input type="text" name="url" maxlength="40" /></li>"""
)
)
def test_with_data(self):
self.assertEqual(Category.objects.count(), 0)
@ -989,7 +989,7 @@ class OldFormForXTests(TestCase):
'pub_date': '1984-02-06',
'writer': six.text_type(w_royko.pk),
'article': 'Hello.'
}, instance=art)
}, instance=art)
self.assertEqual(f.errors, {})
self.assertEqual(f.is_valid(), True)
test_art = f.save()
@ -1002,7 +1002,7 @@ class OldFormForXTests(TestCase):
'headline': 'New headline',
'slug': 'new-headline',
'pub_date': '1988-01-04'
}, auto_id=False, instance=art)
}, auto_id=False, instance=art)
self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>''')
@ -1073,7 +1073,7 @@ class OldFormForXTests(TestCase):
'writer': six.text_type(w_royko.pk),
'article': 'Hello.',
'categories': [six.text_type(c1.id), six.text_type(c2.id)]
}, instance=new_art)
}, instance=new_art)
new_art = f.save()
self.assertEqual(new_art.id == art_id_1, True)
new_art = Article.objects.get(id=art_id_1)
@ -1619,7 +1619,7 @@ class OldFormForXTests(TestCase):
f = OptionalImageFileForm(
data={'description': 'And a final one'},
files={'image': SimpleUploadedFile('test4.png', image_data2)}
)
)
self.assertEqual(f.is_valid(), True)
instance = f.save()
self.assertEqual(instance.image.name, 'tests/test4.png')

View File

@ -203,7 +203,7 @@ class InlineFormsetTests(TestCase):
self.assertQuerysetEqual(
dalnet.host_set.order_by("hostname"),
["<Host: matrix.de.eu.dal.net>", "<Host: tranquility.hub.dal.net>"]
)
)
def test_initial_data(self):
user = User.objects.create(username="bibi", serial=1)

View File

@ -123,13 +123,13 @@ class ModelTests(TestCase):
self.assertQuerysetEqual(
Party.objects.filter(when__year=1), [
datetime.date(1, 3, 3),
],
],
attrgetter("when")
)
self.assertQuerysetEqual(
Party.objects.filter(when__year='1'), [
datetime.date(1, 3, 3),
],
],
attrgetter("when")
)

View File

@ -253,7 +253,7 @@ class ModelPaginationTests(TestCase):
"<Article: Article 3>",
"<Article: Article 4>",
"<Article: Article 5>"
],
],
ordered=False
)
self.assertTrue(p.has_next())
@ -273,7 +273,7 @@ class ModelPaginationTests(TestCase):
"<Article: Article 7>",
"<Article: Article 8>",
"<Article: Article 9>"
],
],
ordered=False
)
self.assertFalse(p.has_next())
@ -304,7 +304,7 @@ class ModelPaginationTests(TestCase):
self.assertQuerysetEqual(p[slice(2)], [
"<Article: Article 1>",
"<Article: Article 2>",
]
]
)
# After __getitem__ is called, object_list is a list
self.assertIsInstance(p.object_list, list)

View File

@ -637,7 +637,7 @@ class Ticket19607Tests(TestCase):
for id, name1, name2 in [
(1, 'einfach', 'simple'),
(2, 'schwierig', 'difficult'),
]:
]:
LessonEntry.objects.create(id=id, name1=name1, name2=name2)
for id, lesson_entry_id, name in [
@ -645,7 +645,7 @@ class Ticket19607Tests(TestCase):
(2, 1, 'simple'),
(3, 2, 'schwierig'),
(4, 2, 'difficult'),
]:
]:
WordEntry.objects.create(id=id, lesson_entry_id=lesson_entry_id, name=name)
def test_bug(self):

View File

@ -480,7 +480,7 @@ class HostValidationTests(SimpleTestCase):
'forward.com', 'example.com', 'internal.com', '12.34.56.78',
'[2001:19f0:feee::dead:beef:cafe]', 'xn--4ca9at.com',
'.multitenant.com', 'INSENSITIVE.com',
])
])
def test_http_get_host(self):
# Check if X_FORWARDED_HOST is provided.
request = HttpRequest()

View File

@ -168,7 +168,7 @@ def setup(verbosity, test_labels):
match = lambda label: (
module_label == label or # exact match
module_label.startswith(label + '.') # ancestor match
)
)
module_found_in_labels = any(match(l) for l in test_labels_set)

View File

@ -68,7 +68,7 @@ class SelectForUpdateTests(TransactionTestCase):
sql = 'SELECT * FROM %(db_table)s %(for_update)s;' % {
'db_table': Person._meta.db_table,
'for_update': self.new_connection.ops.for_update_sql(),
}
}
self.cursor.execute(sql, ())
self.cursor.fetchone()

View File

@ -559,7 +559,7 @@ def naturalKeyTest(format, self):
for format in [
f for f in serializers.get_serializer_formats()
if not isinstance(serializers.get_serializer(f), serializers.BadSerializer)
]:
]:
setattr(SerializerTests, 'test_' + format + '_serializer', curry(serializerTest, format))
setattr(SerializerTests, 'test_' + format + '_natural_key_serializer', curry(naturalKeySerializerTest, format))
setattr(SerializerTests, 'test_' + format + '_serializer_fields', curry(fieldsTest, format))

View File

@ -33,7 +33,7 @@ class TestSigner(TestCase):
signer.signature('hello'),
signing.base64_hmac('extra-salt' + 'signer',
'hello', 'predictable-secret').decode()
)
)
self.assertNotEqual(
signing.Signer('predictable-secret', salt='one').signature('hello'),
signing.Signer('predictable-secret', salt='two').signature('hello'))

View File

@ -81,7 +81,7 @@ def simple_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
return "simple_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)
)
simple_unlimited_args_kwargs.anything = "Expected simple_unlimited_args_kwargs __dict__"
@register.simple_tag(takes_context=True)
@ -232,7 +232,7 @@ def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)}
)}
inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
@ -303,7 +303,7 @@ def assignment_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
return "assignment_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)
)
assignment_unlimited_args_kwargs.anything = "Expected assignment_unlimited_args_kwargs __dict__"
@register.assignment_tag(takes_context=True)

View File

@ -112,7 +112,7 @@ class CachedLoader(unittest.TestCase):
settings.TEMPLATE_LOADERS = (
('django.template.loaders.cached.Loader', (
'django.template.loaders.filesystem.Loader',
)
)
),
)
def tearDown(self):

View File

@ -123,7 +123,7 @@ class ParserTests(TestCase):
'1|two_arguments',
'1|two_arguments:"1"',
'1|two_one_opt_arg',
):
):
with self.assertRaises(TemplateSyntaxError):
FilterExpression(expr, p)
for expr in (
@ -135,5 +135,5 @@ class ParserTests(TestCase):
'1|one_opt_argument:"1"',
# Not supplying all
'1|two_one_opt_arg:"1"',
):
):
FilterExpression(expr, p)

View File

@ -152,7 +152,7 @@ class SimpleTemplateResponseTest(TestCase):
response = SimpleTemplateResponse('first/test.html', {
'value': 123,
'fn': datetime.now,
})
})
self.assertRaises(ContentNotRenderedError,
pickle.dumps, response)
@ -180,7 +180,7 @@ class SimpleTemplateResponseTest(TestCase):
response = SimpleTemplateResponse('first/test.html', {
'value': 123,
'fn': datetime.now,
})
})
self.assertRaises(ContentNotRenderedError,
pickle.dumps, response)
@ -193,7 +193,7 @@ class SimpleTemplateResponseTest(TestCase):
response = SimpleTemplateResponse('first/test.html', {
'value': 123,
'fn': datetime.now,
})
})
response.cookies['key'] = 'value'
@ -286,7 +286,7 @@ class TemplateResponseTest(TestCase):
response = SimpleTemplateResponse('first/test.html', {
'value': 123,
'fn': datetime.now,
})
})
self.assertRaises(ContentNotRenderedError,
pickle.dumps, response)

View File

@ -573,7 +573,7 @@ class TemplateTests(TransRealMixin, TestCase):
('', False, normal_string_result),
(expected_invalid_str, False, invalid_string_result),
('', True, template_debug_result)
]:
]:
settings.TEMPLATE_STRING_IF_INVALID = invalid_str
settings.TEMPLATE_DEBUG = template_debug
for is_cached in (False, True):

View File

@ -355,7 +355,7 @@ class DeprecationDisplayTest(AdminScriptTestCase):
def setUp(self):
settings = {
'DATABASES': '{"default": {"ENGINE":"django.db.backends.sqlite3", "NAME":":memory:"}}'
}
}
self.write_settings('settings.py', sdict=settings)
def tearDown(self):

View File

@ -49,7 +49,7 @@ class TestUtilsHtml(TestCase):
fourth=html.mark_safe("<i>safe again</i>")
),
"&lt; Dangerous &gt; <b>safe</b> &lt; dangerous again <i>safe again</i>"
)
)
def test_linebreaks(self):
f = html.linebreaks

View File

@ -103,7 +103,7 @@ class JsTokensTest(TestCase):
"id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', "punct )",
"punct .", "id replace", "punct (", r'regex /"/g', "punct ,", r'string "\\\""', "punct )", "punct +",
r'string "\")"', "punct ;"]),
]
]
def make_function(input, toks):
def test_func(self):

View File

@ -43,7 +43,7 @@ class GetUniqueCheckTests(unittest.TestCase):
[(UniqueForDateModel, 'date', 'count', 'start_date'),
(UniqueForDateModel, 'year', 'count', 'end_date'),
(UniqueForDateModel, 'month', 'order', 'end_date')]
), m._get_unique_checks()
), m._get_unique_checks()
)
def test_unique_for_date_exclusion(self):
@ -52,7 +52,7 @@ class GetUniqueCheckTests(unittest.TestCase):
[(UniqueForDateModel, ('id',))],
[(UniqueForDateModel, 'year', 'count', 'end_date'),
(UniqueForDateModel, 'month', 'order', 'end_date')]
), m._get_unique_checks(exclude='start_date')
), m._get_unique_checks(exclude='start_date')
)
class PerformUniqueChecksTest(TestCase):

View File

@ -59,7 +59,7 @@ class StaticTests(SimpleTestCase):
HTTP_IF_MODIFIED_SINCE='Mon, 18 Jan 2038 05:14:07 GMT'
# This is 24h before max Unix time. Remember to fix Django and
# update this test well before 2038 :)
)
)
self.assertIsInstance(response, HttpResponseNotModified)
def test_invalid_if_modified_since(self):

View File

@ -154,7 +154,7 @@ def send_log(request, exc_info):
admin_email_handler = [
h for h in logger.handlers
if h.__class__.__name__ == "AdminEmailHandler"
][0]
][0]
orig_filters = admin_email_handler.filters
admin_email_handler.filters = []
admin_email_handler.include_html = True

View File

@ -34,7 +34,7 @@ class WSGITest(TestCase):
PATH_INFO="/",
CONTENT_TYPE="text/html; charset=utf-8",
REQUEST_METHOD="GET"
)
)
response_data = {}

View File

@ -7,4 +7,4 @@ def helloworld(request):
urlpatterns = patterns(
"",
url("^$", helloworld)
)
)