From c3791463a5a9674f8e0148fbab57eae23c138896 Mon Sep 17 00:00:00 2001 From: Jason Myers Date: Sat, 2 Nov 2013 16:34:05 -0500 Subject: Fixing E302 Errors Signed-off-by: Jason Myers --- tests/multiple_database/tests.py | 36 +++++++++++++++++++++--------------- 1 file changed, 21 insertions(+), 15 deletions(-) (limited to 'tests/multiple_database') diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index f7c5862167..046b8fb14b 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -50,7 +50,8 @@ class QueryTestCase(TestCase): except Book.DoesNotExist: self.fail('"Pro Django" should exist on default database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('other').get, title="Pro Django" ) @@ -61,7 +62,8 @@ class QueryTestCase(TestCase): except Book.DoesNotExist: self.fail('"Dive into Python" should exist on default database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('other').get, title="Dive into Python" ) @@ -84,11 +86,13 @@ class QueryTestCase(TestCase): except Book.DoesNotExist: self.fail('"Pro Django" should exist on other database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.get, title="Pro Django" ) - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('default').get, title="Pro Django" ) @@ -98,11 +102,13 @@ class QueryTestCase(TestCase): except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.get, title="Dive into Python" ) - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('default').get, title="Dive into Python" ) @@ -164,14 +170,14 @@ class QueryTestCase(TestCase): # Check that queries work across m2m joins self.assertEqual(list(Book.objects.using('default').filter(authors__name='Marty Alchin').values_list('title', flat=True)), - ['Pro Django']) + ['Pro Django']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Marty Alchin').values_list('title', flat=True)), - []) + []) self.assertEqual(list(Book.objects.using('default').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) + []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) # Reget the objects to clear caches dive = Book.objects.using('other').get(title="Dive into Python") @@ -179,10 +185,10 @@ class QueryTestCase(TestCase): # Retrive related object by descriptor. Related objects should be database-baound self.assertEqual(list(dive.authors.all().values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) self.assertEqual(list(mark.book_set.all().values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) def test_m2m_forward_operations(self): "M2M forward manipulations are all constrained to a single DB" @@ -198,13 +204,13 @@ class QueryTestCase(TestCase): # Add a second author john = Person.objects.using('other').create(name="John Smith") self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + []) dive.authors.add(john) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) # Remove the second author dive.authors.remove(john) -- cgit v1.3 From 8eec2d93b6e93b8a1107fb3de2acd68d6994d6ec Mon Sep 17 00:00:00 2001 From: coagulant Date: Sun, 3 Nov 2013 01:02:56 +0400 Subject: Fixed all E261 warnings --- django/conf/__init__.py | 2 +- django/conf/global_settings.py | 12 +- django/conf/locale/bg/formats.py | 2 +- django/conf/locale/ca/formats.py | 2 +- django/conf/locale/cs/formats.py | 12 +- django/conf/locale/de/formats.py | 4 +- django/conf/locale/de_CH/formats.py | 6 +- django/conf/locale/en/formats.py | 4 +- django/conf/locale/es/formats.py | 2 +- django/conf/locale/es_AR/formats.py | 6 +- django/conf/locale/es_MX/formats.py | 2 +- django/conf/locale/es_NI/formats.py | 2 +- django/conf/locale/es_PR/formats.py | 2 +- django/conf/locale/et/formats.py | 2 +- django/conf/locale/fi/formats.py | 2 +- django/conf/locale/fr/formats.py | 24 ++-- django/conf/locale/gl/formats.py | 2 +- django/conf/locale/hr/formats.py | 40 +++--- django/conf/locale/hu/formats.py | 10 +- django/conf/locale/it/formats.py | 16 +-- django/conf/locale/ka/formats.py | 2 +- django/conf/locale/ko/formats.py | 2 +- django/conf/locale/lt/formats.py | 2 +- django/conf/locale/lv/formats.py | 4 +- django/conf/locale/mk/formats.py | 32 ++--- django/conf/locale/ml/formats.py | 4 +- django/conf/locale/nb/formats.py | 6 +- django/conf/locale/nn/formats.py | 6 +- django/conf/locale/pl/formats.py | 10 +- django/conf/locale/pt/formats.py | 2 +- django/conf/locale/pt_BR/formats.py | 2 +- django/conf/locale/ru/formats.py | 18 +-- django/conf/locale/sk/formats.py | 12 +- django/conf/locale/sr/formats.py | 32 ++--- django/conf/locale/sr_Latn/formats.py | 32 ++--- django/conf/locale/sv/formats.py | 2 +- django/conf/locale/tr/formats.py | 10 +- django/contrib/admin/helpers.py | 6 +- django/contrib/admin/options.py | 2 +- django/contrib/admin/templatetags/admin_list.py | 8 +- django/contrib/admin/templatetags/admin_modify.py | 2 +- django/contrib/admin/utils.py | 12 +- django/contrib/admin/validation.py | 8 +- django/contrib/admin/views/main.py | 8 +- django/contrib/admin/widgets.py | 2 +- django/contrib/contenttypes/generic.py | 2 +- django/contrib/flatpages/middleware.py | 2 +- django/contrib/formtools/preview.py | 6 +- django/contrib/gis/db/backends/mysql/operations.py | 6 +- .../contrib/gis/db/backends/oracle/operations.py | 6 +- .../contrib/gis/db/backends/postgis/operations.py | 2 +- .../gis/db/backends/spatialite/operations.py | 6 +- django/contrib/gis/db/models/fields.py | 2 +- django/contrib/gis/db/models/query.py | 4 +- django/contrib/gis/gdal/geometries.py | 6 +- django/contrib/gis/gdal/prototypes/ds.py | 2 +- django/contrib/gis/gdal/prototypes/geom.py | 2 +- django/contrib/gis/gdal/tests/test_ds.py | 8 +- django/contrib/gis/gdal/tests/test_envelope.py | 2 +- django/contrib/gis/gdal/tests/test_geom.py | 38 +++--- django/contrib/gis/gdal/tests/test_srs.py | 4 +- django/contrib/gis/geoip/tests.py | 6 +- django/contrib/gis/geos/linestring.py | 8 +- django/contrib/gis/geos/prototypes/errcheck.py | 2 +- django/contrib/gis/geos/prototypes/misc.py | 2 +- django/contrib/gis/geos/tests/test_geos.py | 56 ++++----- django/contrib/gis/geos/tests/test_mutable_list.py | 6 +- django/contrib/gis/maps/google/gmap.py | 6 +- django/contrib/gis/maps/google/zoom.py | 14 +-- django/contrib/gis/tests/distapp/tests.py | 8 +- django/contrib/gis/tests/geoapp/models.py | 8 +- django/contrib/gis/tests/geoapp/test_feeds.py | 4 +- django/contrib/gis/tests/geoapp/test_sitemaps.py | 2 +- django/contrib/gis/tests/geoapp/tests.py | 24 ++-- django/contrib/gis/tests/geogapp/tests.py | 4 +- django/contrib/gis/tests/layermap/models.py | 6 +- django/contrib/gis/tests/layermap/tests.py | 10 +- django/contrib/gis/tests/test_spatialrefsys.py | 4 +- django/contrib/gis/utils/layermapping.py | 6 +- django/contrib/messages/storage/cookie.py | 2 +- django/contrib/messages/tests/test_cookie.py | 2 +- django/contrib/sessions/models.py | 2 +- django/contrib/sessions/tests.py | 2 +- django/core/cache/backends/memcached.py | 2 +- django/core/files/uploadhandler.py | 2 +- django/core/handlers/base.py | 4 +- django/core/handlers/wsgi.py | 2 +- django/core/management/__init__.py | 6 +- django/core/management/commands/inspectdb.py | 6 +- django/core/urlresolvers.py | 6 +- django/core/validators.py | 2 +- django/db/backends/mysql/base.py | 6 +- django/db/backends/oracle/creation.py | 2 +- django/db/backends/oracle/introspection.py | 4 +- .../backends/postgresql_psycopg2/introspection.py | 2 +- .../db/backends/postgresql_psycopg2/operations.py | 4 +- django/db/backends/sqlite3/base.py | 2 +- django/db/backends/sqlite3/introspection.py | 2 +- django/db/backends/utils.py | 10 +- django/db/models/__init__.py | 2 +- django/db/models/base.py | 2 +- django/db/models/fields/__init__.py | 2 +- django/db/models/query.py | 8 +- django/db/models/sql/query.py | 2 +- django/http/multipartparser.py | 4 +- django/http/request.py | 14 +-- django/middleware/cache.py | 6 +- django/templatetags/cache.py | 2 +- django/test/_doctest.py | 16 +-- django/test/simple.py | 4 +- django/utils/dictconfig.py | 66 +++++----- django/views/debug.py | 2 +- docs/conf.py | 2 +- setup.cfg | 2 +- tests/admin_changelist/admin.py | 2 +- tests/admin_filters/models.py | 2 +- tests/admin_filters/tests.py | 4 +- tests/admin_inlines/admin.py | 2 +- tests/admin_ordering/tests.py | 2 +- tests/admin_views/admin.py | 8 +- tests/admin_views/customadmin.py | 4 +- tests/admin_views/models.py | 2 +- tests/admin_widgets/tests.py | 4 +- tests/aggregation_regress/tests.py | 2 +- tests/cache/tests.py | 6 +- tests/comment_tests/tests/test_moderation_views.py | 6 +- tests/datatypes/tests.py | 2 +- tests/file_uploads/uploadhandler.py | 2 +- tests/forms_tests/tests/test_forms.py | 2 +- tests/forms_tests/tests/test_formsets.py | 140 ++++++++++----------- tests/forms_tests/tests/test_input_formats.py | 10 +- tests/generic_inline_admin/tests.py | 6 +- tests/httpwrappers/tests.py | 14 +-- tests/i18n/test_extraction.py | 2 +- tests/i18n/tests.py | 2 +- tests/invalid_models/invalid_models/models.py | 2 +- tests/m2m_and_m2o/tests.py | 4 +- tests/max_lengths/tests.py | 2 +- tests/model_forms/tests.py | 12 +- tests/model_formsets/tests.py | 110 ++++++++-------- tests/modeladmin/models.py | 2 +- tests/multiple_database/tests.py | 12 +- tests/null_fk/tests.py | 2 +- tests/queryset_pickle/tests.py | 2 +- tests/requests/tests.py | 10 +- tests/serializers_regress/tests.py | 2 +- tests/template_tests/filters.py | 2 +- tests/template_tests/tests.py | 2 +- tests/test_client/tests.py | 2 +- tests/test_client_regress/tests.py | 6 +- tests/view_tests/__init__.py | 2 +- tests/view_tests/tests/test_defaults.py | 4 +- 152 files changed, 630 insertions(+), 630 deletions(-) (limited to 'tests/multiple_database') diff --git a/django/conf/__init__.py b/django/conf/__init__.py index 7a915f1486..5245ff9e25 100644 --- a/django/conf/__init__.py +++ b/django/conf/__init__.py @@ -36,7 +36,7 @@ class LazySettings(LazyObject): """ try: settings_module = os.environ[ENVIRONMENT_VARIABLE] - if not settings_module: # If it's set but is an empty string. + if not settings_module: # If it's set but is an empty string. raise KeyError except KeyError: desc = ("setting %s" % name) if name else "settings" diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py index 377c010b32..19d70eeb3e 100644 --- a/django/conf/global_settings.py +++ b/django/conf/global_settings.py @@ -302,7 +302,7 @@ FILE_UPLOAD_HANDLERS = ( # Maximum size, in bytes, of a request before it will be streamed to the # file system instead of into memory. -FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB +FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 # i.e. 2.5 MB # Directory in which upload streamed files will be temporarily saved. A value of # `None` will make Django use the operating system's default temporary directory @@ -360,11 +360,11 @@ SHORT_DATETIME_FORMAT = 'm/d/Y P' # http://docs.python.org/library/datetime.html#strftime-behavior # * Note that these format strings are different from the ones to display dates DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' - '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' - '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' - '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' - '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' + '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' + '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' + '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' + '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' + '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ) # Default formats to be used when parsing times from input boxes, in order diff --git a/django/conf/locale/bg/formats.py b/django/conf/locale/bg/formats.py index 4472600398..e1a8a820e3 100644 --- a/django/conf/locale/bg/formats.py +++ b/django/conf/locale/bg/formats.py @@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = ' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space # NUMBER_GROUPING = diff --git a/django/conf/locale/ca/formats.py b/django/conf/locale/ca/formats.py index 9ccddbb24d..392eb48c1c 100644 --- a/django/conf/locale/ca/formats.py +++ b/django/conf/locale/ca/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e\l Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y G:i' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior diff --git a/django/conf/locale/cs/formats.py b/django/conf/locale/cs/formats.py index 42ca212392..fd445fac6a 100644 --- a/django/conf/locale/cs/formats.py +++ b/django/conf/locale/cs/formats.py @@ -12,34 +12,34 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( '%d.%m.%Y', '%d.%m.%y', # '05.01.2006', '05.01.06' - '%d. %m. %Y', '%d. %m. %y', # '5. 1. 2006', '5. 1. 06' + '%d. %m. %Y', '%d. %m. %y', # '5. 1. 2006', '5. 1. 06' # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) # Kept ISO formats as one is in first position TIME_INPUT_FORMATS = ( - '%H:%M:%S', # '04:30:59' + '%H:%M:%S', # '04:30:59' '%H.%M', # '04.30' '%H:%M', # '04:30' ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '05.01.2006 04:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '05.01.2006 04:30:59.000200' + '%d.%m.%Y %H:%M:%S.%f', # '05.01.2006 04:30:59.000200' '%d.%m.%Y %H.%M', # '05.01.2006 04.30' '%d.%m.%Y %H:%M', # '05.01.2006 04:30' '%d.%m.%Y', # '05.01.2006' '%d. %m. %Y %H:%M:%S', # '05. 01. 2006 04:30:59' - '%d. %m. %Y %H:%M:%S.%f', # '05. 01. 2006 04:30:59.000200' + '%d. %m. %Y %H:%M:%S.%f', # '05. 01. 2006 04:30:59.000200' '%d. %m. %Y %H.%M', # '05. 01. 2006 04.30' '%d. %m. %Y %H:%M', # '05. 01. 2006 04:30' '%d. %m. %Y', # '05. 01. 2006' '%Y-%m-%d %H.%M', # '2006-01-05 04.30' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/de/formats.py b/django/conf/locale/de/formats.py index b3731a3617..b57f6213a5 100644 --- a/django/conf/locale/de/formats.py +++ b/django/conf/locale/de/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior @@ -22,7 +22,7 @@ DATE_INPUT_FORMATS = ( ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' ) diff --git a/django/conf/locale/de_CH/formats.py b/django/conf/locale/de_CH/formats.py index bf8a5ce372..4b1678cffd 100644 --- a/django/conf/locale/de_CH/formats.py +++ b/django/conf/locale/de_CH/formats.py @@ -13,7 +13,7 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior @@ -23,7 +23,7 @@ DATE_INPUT_FORMATS = ( ) DATETIME_INPUT_FORMATS = ( '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' '%d.%m.%Y %H:%M', # '25.10.2006 14:30' '%d.%m.%Y', # '25.10.2006' ) @@ -34,5 +34,5 @@ DATETIME_INPUT_FORMATS = ( # For details, please refer to http://www.bk.admin.ch/dokumentation/sprachen/04915/05016/index.html?lang=de # (in German) and the documentation DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/en/formats.py b/django/conf/locale/en/formats.py index 5accf9e3d2..279cd3c518 100644 --- a/django/conf/locale/en/formats.py +++ b/django/conf/locale/en/formats.py @@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' -FIRST_DAY_OF_WEEK = 0 # Sunday +FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' + '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' diff --git a/django/conf/locale/es/formats.py b/django/conf/locale/es/formats.py index 08029a876e..dee0a889f6 100644 --- a/django/conf/locale/es/formats.py +++ b/django/conf/locale/es/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior diff --git a/django/conf/locale/es_AR/formats.py b/django/conf/locale/es_AR/formats.py index 41c732f7b8..37faa80b8a 100644 --- a/django/conf/locale/es_AR/formats.py +++ b/django/conf/locale/es_AR/formats.py @@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = r'F Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = r'd/m/Y' SHORT_DATETIME_FORMAT = r'd/m/Y H:i' -FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday +FIRST_DAY_OF_WEEK = 0 # 0: Sunday, 1: Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( - '%d/%m/%Y', # '31/12/2009' - '%d/%m/%y', # '31/12/09' + '%d/%m/%Y', # '31/12/2009' + '%d/%m/%y', # '31/12/09' ) DATETIME_INPUT_FORMATS = ( '%d/%m/%Y %H:%M:%S', diff --git a/django/conf/locale/es_MX/formats.py b/django/conf/locale/es_MX/formats.py index e3ac674ab0..729eee5370 100644 --- a/django/conf/locale/es_MX/formats.py +++ b/django/conf/locale/es_MX/formats.py @@ -24,5 +24,5 @@ DATETIME_INPUT_FORMATS = ( '%d/%m/%y %H:%M', ) DECIMAL_SEPARATOR = '.' # ',' is also official (less common): NOM-008-SCFI-2002 -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/es_NI/formats.py b/django/conf/locale/es_NI/formats.py index 4bdf24e491..2f8d403d85 100644 --- a/django/conf/locale/es_NI/formats.py +++ b/django/conf/locale/es_NI/formats.py @@ -10,7 +10,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' -FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601 +FIRST_DAY_OF_WEEK = 1 # Monday: ISO 8601 DATE_INPUT_FORMATS = ( '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' '%Y%m%d', # '20061025' diff --git a/django/conf/locale/es_PR/formats.py b/django/conf/locale/es_PR/formats.py index 1d4e76c55b..8f5a25ea53 100644 --- a/django/conf/locale/es_PR/formats.py +++ b/django/conf/locale/es_PR/formats.py @@ -10,7 +10,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y H:i' -FIRST_DAY_OF_WEEK = 0 # Sunday +FIRST_DAY_OF_WEEK = 0 # Sunday DATE_INPUT_FORMATS = ( # '31/12/2009', '31/12/09' diff --git a/django/conf/locale/et/formats.py b/django/conf/locale/et/formats.py index 1de3948a2b..5be8131ed6 100644 --- a/django/conf/locale/et/formats.py +++ b/django/conf/locale/et/formats.py @@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'd.m.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = ' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space # NUMBER_GROUPING = diff --git a/django/conf/locale/fi/formats.py b/django/conf/locale/fi/formats.py index da1f003411..b1900a3b7c 100644 --- a/django/conf/locale/fi/formats.py +++ b/django/conf/locale/fi/formats.py @@ -20,5 +20,5 @@ SHORT_DATE_FORMAT = 'j.n.Y' # TIME_INPUT_FORMATS = # DATETIME_INPUT_FORMATS = DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = ' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space # NUMBER_GROUPING = diff --git a/django/conf/locale/fr/formats.py b/django/conf/locale/fr/formats.py index f6c8f40648..7b85807404 100644 --- a/django/conf/locale/fr/formats.py +++ b/django/conf/locale/fr/formats.py @@ -12,25 +12,25 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j N Y' SHORT_DATETIME_FORMAT = 'j N Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( - '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' - '%d.%m.%Y', '%d.%m.%y', # Swiss (fr_CH), '25.10.2006', '25.10.06' + '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' + '%d.%m.%Y', '%d.%m.%y', # Swiss (fr_CH), '25.10.2006', '25.10.06' # '%d %B %Y', '%d %b %Y', # '25 octobre 2006', '25 oct. 2006' ) DATETIME_INPUT_FORMATS = ( - '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' - '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' - '%d/%m/%Y %H:%M', # '25/10/2006 14:30' - '%d/%m/%Y', # '25/10/2006' - '%d.%m.%Y %H:%M:%S', # Swiss (fr_CH), '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # Swiss (fr_CH), '25.10.2006 14:30:59.000200' - '%d.%m.%Y %H:%M', # Swiss (fr_CH), '25.10.2006 14:30' - '%d.%m.%Y', # Swiss (fr_CH), '25.10.2006' + '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' + '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' + '%d/%m/%Y %H:%M', # '25/10/2006 14:30' + '%d/%m/%Y', # '25/10/2006' + '%d.%m.%Y %H:%M:%S', # Swiss (fr_CH), '25.10.2006 14:30:59' + '%d.%m.%Y %H:%M:%S.%f', # Swiss (fr_CH), '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M', # Swiss (fr_CH), '25.10.2006 14:30' + '%d.%m.%Y', # Swiss (fr_CH), '25.10.2006' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/gl/formats.py b/django/conf/locale/gl/formats.py index de592240f0..0facf691a9 100644 --- a/django/conf/locale/gl/formats.py +++ b/django/conf/locale/gl/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = r'F \d\e Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y, H:i' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior diff --git a/django/conf/locale/hr/formats.py b/django/conf/locale/hr/formats.py index 96a724b2b8..a38457a435 100644 --- a/django/conf/locale/hr/formats.py +++ b/django/conf/locale/hr/formats.py @@ -23,26 +23,26 @@ DATE_INPUT_FORMATS = ( '%d. %m. %Y.', '%d. %m. %y.', # '25. 10. 2006.', '25. 10. 06.' ) DATETIME_INPUT_FORMATS = ( - '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' - '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' - '%Y-%m-%d %H:%M', # '2006-10-25 14:30' - '%Y-%m-%d', # '2006-10-25' - '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' - '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' - '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' - '%d.%m.%Y.', # '25.10.2006.' - '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' - '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' - '%d.%m.%y. %H:%M', # '25.10.06. 14:30' - '%d.%m.%y.', # '25.10.06.' - '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' - '%d. %m. %Y. %H:%M:%S.%f',# '25. 10. 2006. 14:30:59.000200' - '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' - '%d. %m. %Y.', # '25. 10. 2006.' - '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' - '%d. %m. %y. %H:%M:%S.%f',# '25. 10. 06. 14:30:59.000200' - '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' - '%d. %m. %y.', # '25. 10. 06.' + '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' + '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' + '%Y-%m-%d %H:%M', # '2006-10-25 14:30' + '%Y-%m-%d', # '2006-10-25' + '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' + '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' + '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' + '%d.%m.%Y.', # '25.10.2006.' + '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' + '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' + '%d.%m.%y. %H:%M', # '25.10.06. 14:30' + '%d.%m.%y.', # '25.10.06.' + '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' + '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' + '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' + '%d. %m. %Y.', # '25. 10. 2006.' + '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' + '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' + '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' + '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = ',' diff --git a/django/conf/locale/hu/formats.py b/django/conf/locale/hu/formats.py index 9b6630d775..7e499da4ee 100644 --- a/django/conf/locale/hu/formats.py +++ b/django/conf/locale/hu/formats.py @@ -12,23 +12,23 @@ YEAR_MONTH_FORMAT = 'Y. F' MONTH_DAY_FORMAT = 'F j.' SHORT_DATE_FORMAT = 'Y.m.d.' SHORT_DATETIME_FORMAT = 'Y.m.d. G.i.s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( - '%Y.%m.%d.', # '2006.10.25.' + '%Y.%m.%d.', # '2006.10.25.' ) TIME_INPUT_FORMATS = ( - '%H.%M.%S', # '14.30.59' + '%H.%M.%S', # '14.30.59' '%H.%M', # '14.30' ) DATETIME_INPUT_FORMATS = ( '%Y.%m.%d. %H.%M.%S', # '2006.10.25. 14.30.59' - '%Y.%m.%d. %H.%M.%S.%f', # '2006.10.25. 14.30.59.000200' + '%Y.%m.%d. %H.%M.%S.%f', # '2006.10.25. 14.30.59.000200' '%Y.%m.%d. %H.%M', # '2006.10.25. 14.30' '%Y.%m.%d.', # '2006.10.25.' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = ' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/it/formats.py b/django/conf/locale/it/formats.py index b12e478ccb..368535d293 100644 --- a/django/conf/locale/it/formats.py +++ b/django/conf/locale/it/formats.py @@ -5,14 +5,14 @@ from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date -DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 -TIME_FORMAT = 'H:i:s' # 14:30:59 -DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59 -YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006 -MONTH_DAY_FORMAT = 'j/F' # 10/2006 -SHORT_DATE_FORMAT = 'd/m/Y' # 25/12/2009 -SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # 25/10/2009 14:30:59 -FIRST_DAY_OF_WEEK = 1 # Lunedì +DATE_FORMAT = 'd F Y' # 25 Ottobre 2006 +TIME_FORMAT = 'H:i:s' # 14:30:59 +DATETIME_FORMAT = 'l d F Y H:i:s' # Mercoledì 25 Ottobre 2006 14:30:59 +YEAR_MONTH_FORMAT = 'F Y' # Ottobre 2006 +MONTH_DAY_FORMAT = 'j/F' # 10/2006 +SHORT_DATE_FORMAT = 'd/m/Y' # 25/12/2009 +SHORT_DATETIME_FORMAT = 'd/m/Y H:i:s' # 25/10/2009 14:30:59 +FIRST_DAY_OF_WEEK = 1 # Lunedì # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior diff --git a/django/conf/locale/ka/formats.py b/django/conf/locale/ka/formats.py index bb26bec6be..1d2eb5f9cb 100644 --- a/django/conf/locale/ka/formats.py +++ b/django/conf/locale/ka/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F, Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'j.M.Y' SHORT_DATETIME_FORMAT = 'j.M.Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # (Monday) +FIRST_DAY_OF_WEEK = 1 # (Monday) # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior diff --git a/django/conf/locale/ko/formats.py b/django/conf/locale/ko/formats.py index 28b4d06ca2..29e57f136c 100644 --- a/django/conf/locale/ko/formats.py +++ b/django/conf/locale/ko/formats.py @@ -18,7 +18,7 @@ SHORT_DATETIME_FORMAT = 'Y-n-j H:i' # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' + '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' diff --git a/django/conf/locale/lt/formats.py b/django/conf/locale/lt/formats.py index 1bff4d9861..41dab5f53b 100644 --- a/django/conf/locale/lt/formats.py +++ b/django/conf/locale/lt/formats.py @@ -17,7 +17,7 @@ FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' + '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' diff --git a/django/conf/locale/lv/formats.py b/django/conf/locale/lv/formats.py index c2c9f9da37..2b281d810f 100644 --- a/django/conf/locale/lv/formats.py +++ b/django/conf/locale/lv/formats.py @@ -18,7 +18,7 @@ FIRST_DAY_OF_WEEK = 1 # Monday # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' + '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' ) TIME_INPUT_FORMATS = ( '%H:%M:%S', # '14:30:59' @@ -45,5 +45,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = ' ' # Non-breaking space +THOUSAND_SEPARATOR = ' ' # Non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/mk/formats.py b/django/conf/locale/mk/formats.py index 2a0df6c43f..fe33070786 100644 --- a/django/conf/locale/mk/formats.py +++ b/django/conf/locale/mk/formats.py @@ -22,22 +22,22 @@ DATE_INPUT_FORMATS = ( ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' - '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' - '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' - '%d.%m.%Y.', # '25.10.2006.' - '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' - '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' - '%d.%m.%y. %H:%M', # '25.10.06. 14:30' - '%d.%m.%y.', # '25.10.06.' - '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' - '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' - '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' - '%d. %m. %Y.', # '25. 10. 2006.' - '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' - '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' - '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' - '%d. %m. %y.', # '25. 10. 06.' + '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' + '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' + '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' + '%d.%m.%Y.', # '25.10.2006.' + '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' + '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' + '%d.%m.%y. %H:%M', # '25.10.06. 14:30' + '%d.%m.%y.', # '25.10.06.' + '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' + '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' + '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' + '%d. %m. %Y.', # '25. 10. 2006.' + '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' + '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' + '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' + '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = ',' diff --git a/django/conf/locale/ml/formats.py b/django/conf/locale/ml/formats.py index 5accf9e3d2..279cd3c518 100644 --- a/django/conf/locale/ml/formats.py +++ b/django/conf/locale/ml/formats.py @@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'F j' SHORT_DATE_FORMAT = 'm/d/Y' SHORT_DATETIME_FORMAT = 'm/d/Y P' -FIRST_DAY_OF_WEEK = 0 # Sunday +FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' + '%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' diff --git a/django/conf/locale/nb/formats.py b/django/conf/locale/nb/formats.py index 8f976d7045..5bf43af0d4 100644 --- a/django/conf/locale/nb/formats.py +++ b/django/conf/locale/nb/formats.py @@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' + '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' @@ -38,5 +38,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/nn/formats.py b/django/conf/locale/nn/formats.py index 528ae30107..ca7d2e294c 100644 --- a/django/conf/locale/nn/formats.py +++ b/django/conf/locale/nn/formats.py @@ -12,13 +12,13 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y H:i' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' + '%Y-%m-%d', '%d.%m.%Y', '%d.%m.%y', # '2006-10-25', '25.10.2006', '25.10.06' # '%d. %b %Y', '%d %b %Y', # '25. okt 2006', '25 okt 2006' # '%d. %b. %Y', '%d %b. %Y', # '25. okt. 2006', '25 okt. 2006' # '%d. %B %Y', '%d %B %Y', # '25. oktober 2006', '25 oktober 2006' @@ -39,5 +39,5 @@ DATETIME_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/pl/formats.py b/django/conf/locale/pl/formats.py index 25cfc793cf..5997839477 100644 --- a/django/conf/locale/pl/formats.py +++ b/django/conf/locale/pl/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j F' SHORT_DATE_FORMAT = 'd-m-Y' SHORT_DATETIME_FORMAT = 'd-m-Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior @@ -22,10 +22,10 @@ DATE_INPUT_FORMATS = ( # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' - '%d.%m.%Y %H:%M', # '25.10.2006 14:30' - '%d.%m.%Y', # '25.10.2006' + '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M', # '25.10.2006 14:30' + '%d.%m.%Y', # '25.10.2006' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = ' ' diff --git a/django/conf/locale/pt/formats.py b/django/conf/locale/pt/formats.py index 9452428dd9..6141176760 100644 --- a/django/conf/locale/pt/formats.py +++ b/django/conf/locale/pt/formats.py @@ -18,7 +18,7 @@ FIRST_DAY_OF_WEEK = 0 # Sunday # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior # Kept ISO formats as they are in first position DATE_INPUT_FORMATS = ( - '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' + '%Y-%m-%d', '%d/%m/%Y', '%d/%m/%y', # '2006-10-25', '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) diff --git a/django/conf/locale/pt_BR/formats.py b/django/conf/locale/pt_BR/formats.py index a5ec333d50..6057a21056 100644 --- a/django/conf/locale/pt_BR/formats.py +++ b/django/conf/locale/pt_BR/formats.py @@ -17,7 +17,7 @@ FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = ( - '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' + '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' # '%d de %b de %Y', '%d de %b, %Y', # '25 de Out de 2006', '25 Out, 2006' # '%d de %B de %Y', '%d de %B, %Y', # '25 de Outubro de 2006', '25 de Outubro, 2006' ) diff --git a/django/conf/locale/ru/formats.py b/django/conf/locale/ru/formats.py index 413ce2788b..2cc5001c6a 100644 --- a/django/conf/locale/ru/formats.py +++ b/django/conf/locale/ru/formats.py @@ -21,15 +21,15 @@ DATE_INPUT_FORMATS = ( '%d.%m.%y', # '25.10.06' ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' - '%d.%m.%Y %H:%M', # '25.10.2006 14:30' - '%d.%m.%Y', # '25.10.2006' - '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' - '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' - '%d.%m.%y %H:%M', # '25.10.06 14:30' - '%d.%m.%y', # '25.10.06' + '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M', # '25.10.2006 14:30' + '%d.%m.%Y', # '25.10.2006' + '%d.%m.%y %H:%M:%S', # '25.10.06 14:30:59' + '%d.%m.%y %H:%M:%S.%f', # '25.10.06 14:30:59.000200' + '%d.%m.%y %H:%M', # '25.10.06 14:30' + '%d.%m.%y', # '25.10.06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/sk/formats.py b/django/conf/locale/sk/formats.py index 6ff8ca791b..dfbd1a681f 100644 --- a/django/conf/locale/sk/formats.py +++ b/django/conf/locale/sk/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'j. F' SHORT_DATE_FORMAT = 'd.m.Y' SHORT_DATETIME_FORMAT = 'd.m.Y G:i:s' -FIRST_DAY_OF_WEEK = 1 # Monday +FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior @@ -22,11 +22,11 @@ DATE_INPUT_FORMATS = ( # '%d. %B %Y', '%d. %b. %Y', # '25. October 2006', '25. Oct. 2006' ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' - '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' - '%d.%m.%Y %H:%M', # '25.10.2006 14:30' - '%d.%m.%Y', # '25.10.2006' + '%d.%m.%Y %H:%M:%S', # '25.10.2006 14:30:59' + '%d.%m.%Y %H:%M:%S.%f', # '25.10.2006 14:30:59.000200' + '%d.%m.%Y %H:%M', # '25.10.2006 14:30' + '%d.%m.%Y', # '25.10.2006' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/sr/formats.py b/django/conf/locale/sr/formats.py index 8e9e9a487e..86d63e42f1 100644 --- a/django/conf/locale/sr/formats.py +++ b/django/conf/locale/sr/formats.py @@ -24,22 +24,22 @@ DATE_INPUT_FORMATS = ( # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' - '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' - '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' - '%d.%m.%Y.', # '25.10.2006.' - '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' - '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' - '%d.%m.%y. %H:%M', # '25.10.06. 14:30' - '%d.%m.%y.', # '25.10.06.' - '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' - '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' - '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' - '%d. %m. %Y.', # '25. 10. 2006.' - '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' - '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' - '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' - '%d. %m. %y.', # '25. 10. 06.' + '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' + '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' + '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' + '%d.%m.%Y.', # '25.10.2006.' + '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' + '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' + '%d.%m.%y. %H:%M', # '25.10.06. 14:30' + '%d.%m.%y.', # '25.10.06.' + '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' + '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' + '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' + '%d. %m. %Y.', # '25. 10. 2006.' + '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' + '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' + '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' + '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' diff --git a/django/conf/locale/sr_Latn/formats.py b/django/conf/locale/sr_Latn/formats.py index 8e9e9a487e..86d63e42f1 100644 --- a/django/conf/locale/sr_Latn/formats.py +++ b/django/conf/locale/sr_Latn/formats.py @@ -24,22 +24,22 @@ DATE_INPUT_FORMATS = ( # '%d. %b %Y.', '%d. %B %Y.', # '25. Oct 2006.', '25. October 2006.' ) DATETIME_INPUT_FORMATS = ( - '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' - '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' - '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' - '%d.%m.%Y.', # '25.10.2006.' - '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' - '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' - '%d.%m.%y. %H:%M', # '25.10.06. 14:30' - '%d.%m.%y.', # '25.10.06.' - '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' - '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' - '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' - '%d. %m. %Y.', # '25. 10. 2006.' - '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' - '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' - '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' - '%d. %m. %y.', # '25. 10. 06.' + '%d.%m.%Y. %H:%M:%S', # '25.10.2006. 14:30:59' + '%d.%m.%Y. %H:%M:%S.%f', # '25.10.2006. 14:30:59.000200' + '%d.%m.%Y. %H:%M', # '25.10.2006. 14:30' + '%d.%m.%Y.', # '25.10.2006.' + '%d.%m.%y. %H:%M:%S', # '25.10.06. 14:30:59' + '%d.%m.%y. %H:%M:%S.%f', # '25.10.06. 14:30:59.000200' + '%d.%m.%y. %H:%M', # '25.10.06. 14:30' + '%d.%m.%y.', # '25.10.06.' + '%d. %m. %Y. %H:%M:%S', # '25. 10. 2006. 14:30:59' + '%d. %m. %Y. %H:%M:%S.%f', # '25. 10. 2006. 14:30:59.000200' + '%d. %m. %Y. %H:%M', # '25. 10. 2006. 14:30' + '%d. %m. %Y.', # '25. 10. 2006.' + '%d. %m. %y. %H:%M:%S', # '25. 10. 06. 14:30:59' + '%d. %m. %y. %H:%M:%S.%f', # '25. 10. 06. 14:30:59.000200' + '%d. %m. %y. %H:%M', # '25. 10. 06. 14:30' + '%d. %m. %y.', # '25. 10. 06.' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' diff --git a/django/conf/locale/sv/formats.py b/django/conf/locale/sv/formats.py index 8874da7519..7673d472a1 100644 --- a/django/conf/locale/sv/formats.py +++ b/django/conf/locale/sv/formats.py @@ -37,5 +37,5 @@ DATETIME_INPUT_FORMATS = ( '%m/%d/%y', # '10/25/06' ) DECIMAL_SEPARATOR = ',' -THOUSAND_SEPARATOR = '\xa0' # non-breaking space +THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3 diff --git a/django/conf/locale/tr/formats.py b/django/conf/locale/tr/formats.py index 395fca9114..175def1956 100644 --- a/django/conf/locale/tr/formats.py +++ b/django/conf/locale/tr/formats.py @@ -12,7 +12,7 @@ YEAR_MONTH_FORMAT = 'F Y' MONTH_DAY_FORMAT = 'd F' SHORT_DATE_FORMAT = 'd M Y' SHORT_DATETIME_FORMAT = 'd M Y H:i:s' -FIRST_DAY_OF_WEEK = 1 # Pazartesi +FIRST_DAY_OF_WEEK = 1 # Pazartesi # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior @@ -22,10 +22,10 @@ DATE_INPUT_FORMATS = ( # '%d %B %Y', '%d %b. %Y', # '25 Ekim 2006', '25 Eki. 2006' ) DATETIME_INPUT_FORMATS = ( - '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' - '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' - '%d/%m/%Y %H:%M', # '25/10/2006 14:30' - '%d/%m/%Y', # '25/10/2006' + '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' + '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' + '%d/%m/%Y %H:%M', # '25/10/2006 14:30' + '%d/%m/%Y', # '25/10/2006' ) DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' diff --git a/django/contrib/admin/helpers.py b/django/contrib/admin/helpers.py index ee38fdf1d5..012a14ef64 100644 --- a/django/contrib/admin/helpers.py +++ b/django/contrib/admin/helpers.py @@ -83,7 +83,7 @@ class Fieldset(object): class Fieldline(object): def __init__(self, form, field, readonly_fields=None, model_admin=None): - self.form = form # A django.forms.Form instance + self.form = form # A django.forms.Form instance if not hasattr(field, "__iter__") or isinstance(field, six.text_type): self.fields = [field] else: @@ -110,8 +110,8 @@ class Fieldline(object): class AdminField(object): def __init__(self, form, field, is_first): - self.field = form[field] # A django.forms.BoundField instance - self.is_first = is_first # Whether this field is first on the line + self.field = form[field] # A django.forms.BoundField instance + self.is_first = is_first # Whether this field is first on the line self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput) def label_tag(self): diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index e3514dd82a..6ab842dd61 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -1033,7 +1033,7 @@ class ModelAdmin(BaseModelAdmin): attr = obj._meta.pk.attname value = obj.serializable_value(attr) return SimpleTemplateResponse('admin/popup_response.html', { - 'pk_value': escape(pk_value), # for possible backwards-compatibility + 'pk_value': escape(pk_value), # for possible backwards-compatibility 'value': escape(value), 'obj': escapejs(obj) }) diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index 0b48cb0851..e75f1a2a60 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -136,13 +136,13 @@ def result_headers(cl): new_order_type = {'asc': 'desc', 'desc': 'asc'}[order_type] # build new ordering param - o_list_primary = [] # URL for making this field the primary sort - o_list_remove = [] # URL for removing this field from sort - o_list_toggle = [] # URL for toggling order type for this field + o_list_primary = [] # URL for making this field the primary sort + o_list_remove = [] # URL for removing this field from sort + o_list_toggle = [] # URL for toggling order type for this field make_qs_param = lambda t, n: ('-' if t == 'desc' else '') + str(n) for j, ot in ordering_field_columns.items(): - if j == i: # Same column + if j == i: # Same column param = make_qs_param(new_order_type, j) # We want clicking on this header to bring the ordering to the # front diff --git a/django/contrib/admin/templatetags/admin_modify.py b/django/contrib/admin/templatetags/admin_modify.py index 7665176228..c4ce53fec0 100644 --- a/django/contrib/admin/templatetags/admin_modify.py +++ b/django/contrib/admin/templatetags/admin_modify.py @@ -49,7 +49,7 @@ def submit_row(context): @register.filter def cell_count(inline_admin_form): """Returns the number of cells used in a tabular inline""" - count = 1 # Hidden cell with hidden 'id' field + count = 1 # Hidden cell with hidden 'id' field for fieldset in inline_admin_form: # Loop through all the fields (one per cell) for line in fieldset: diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index 2242f7de58..ed3668907a 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -154,7 +154,7 @@ def get_deleted_objects(objs, opts, user, admin_site, using): class NestedObjects(Collector): def __init__(self, *args, **kwargs): super(NestedObjects, self).__init__(*args, **kwargs) - self.edges = {} # {from_instance: [to_instances]} + self.edges = {} # {from_instance: [to_instances]} self.protected = set() def add_edge(self, source, target): @@ -391,7 +391,7 @@ class NotRelationField(Exception): def get_model_from_relation(field): if isinstance(field, models.related.RelatedObject): return field.model - elif getattr(field, 'rel'): # or isinstance? + elif getattr(field, 'rel'): # or isinstance? return field.rel.to else: raise NotRelationField @@ -412,7 +412,7 @@ def reverse_field_path(model, path): for piece in pieces: field, model, direct, m2m = parent._meta.get_field_by_name(piece) # skip trailing data field if extant: - if len(reversed_path) == len(pieces)-1: # final iteration + if len(reversed_path) == len(pieces)-1: # final iteration try: get_model_from_relation(field) except NotRelationField: @@ -469,8 +469,8 @@ def get_limit_choices_to_from_path(model, path): fields and hasattr(fields[-1], 'rel') and getattr(fields[-1].rel, 'limit_choices_to', None)) if not limit_choices_to: - return models.Q() # empty Q + return models.Q() # empty Q elif isinstance(limit_choices_to, models.Q): - return limit_choices_to # already a Q + return limit_choices_to # already a Q else: - return models.Q(**limit_choices_to) # convert dict to Q + return models.Q(**limit_choices_to) # convert dict to Q diff --git a/django/contrib/admin/validation.py b/django/contrib/admin/validation.py index 12b3bdb211..b2cb0b4181 100644 --- a/django/contrib/admin/validation.py +++ b/django/contrib/admin/validation.py @@ -70,7 +70,7 @@ class BaseValidator(object): def validate_fields(self, cls, model): " Validate that fields only refer to existing fields, doesn't contain duplicates. " # fields - if cls.fields: # default value is None + if cls.fields: # default value is None check_isseq(cls, 'fields', cls.fields) self.check_field_spec(cls, model, cls.fields, 'fields') if cls.fieldsets: @@ -81,7 +81,7 @@ class BaseValidator(object): def validate_fieldsets(self, cls, model): " Validate that fieldsets is properly formatted and doesn't contain duplicates. " from django.contrib.admin.options import flatten_fieldsets - if cls.fieldsets: # default value is None + if cls.fieldsets: # default value is None check_isseq(cls, 'fieldsets', cls.fieldsets) for idx, fieldset in enumerate(cls.fieldsets): check_isseq(cls, 'fieldsets[%d]' % idx, fieldset) @@ -100,7 +100,7 @@ class BaseValidator(object): def validate_exclude(self, cls, model): " Validate that exclude is a sequence without duplicates. " - if cls.exclude: # default value is None + if cls.exclude: # default value is None check_isseq(cls, 'exclude', cls.exclude) if len(cls.exclude) > len(set(cls.exclude)): raise ImproperlyConfigured('There are duplicate field(s) in %s.exclude' % cls.__name__) @@ -384,7 +384,7 @@ class ModelAdminValidator(BaseValidator): class InlineValidator(BaseValidator): def validate_fk_name(self, cls, model): " Validate that fk_name refers to a ForeignKey. " - if cls.fk_name: # default value is None + if cls.fk_name: # default value is None f = get_field(cls, model, 'fk_name', cls.fk_name) if not isinstance(f, models.ForeignKey): raise ImproperlyConfigured("'%s.fk_name is not an instance of " diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py index 04977eeef8..a0ffef90f4 100644 --- a/django/contrib/admin/views/main.py +++ b/django/contrib/admin/views/main.py @@ -130,7 +130,7 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)): """ if not params: params = self.params - lookup_params = params.copy() # a dictionary of the query string + lookup_params = params.copy() # a dictionary of the query string # Remove all the parameters that are globally and systematically # ignored. for ignored in IGNORED_PARAMS: @@ -299,10 +299,10 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)): field_name = self.list_display[int(idx)] order_field = self.get_ordering_field(field_name) if not order_field: - continue # No 'admin_order_field', skip it + continue # No 'admin_order_field', skip it ordering.append(pfx + order_field) except (IndexError, ValueError): - continue # Invalid ordering specified, skip it. + continue # Invalid ordering specified, skip it. # Add the given query's ordering fields, if any. ordering.extend(queryset.query.order_by) @@ -347,7 +347,7 @@ class ChangeList(six.with_metaclass(RenameChangeListMethods)): try: idx = int(idx) except ValueError: - continue # skip it + continue # skip it ordering_fields[idx] = 'desc' if pfx == '-' else 'asc' return ordering_fields diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py index 0066f86b52..a17f875f40 100644 --- a/django/contrib/admin/widgets.py +++ b/django/contrib/admin/widgets.py @@ -164,7 +164,7 @@ class ForeignKeyRawIdWidget(forms.TextInput): else: url = '' if "class" not in attrs: - attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. + attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript code looks for this hook. # TODO: "lookup_id_" is hard-coded here. This should instead use # the correct API to determine the ID dynamically. extra.append(' ' diff --git a/django/contrib/contenttypes/generic.py b/django/contrib/contenttypes/generic.py index 10d3f7d4a5..26af7f0d3f 100644 --- a/django/contrib/contenttypes/generic.py +++ b/django/contrib/contenttypes/generic.py @@ -461,7 +461,7 @@ def generic_inlineformset_factory(model, form=ModelForm, ct_field = opts.get_field(ct_field) if not isinstance(ct_field, models.ForeignKey) or ct_field.rel.to != ContentType: raise Exception("fk_name '%s' is not a ForeignKey to ContentType" % ct_field) - fk_field = opts.get_field(fk_field) # let the exception propagate + fk_field = opts.get_field(fk_field) # let the exception propagate if exclude is not None: exclude = list(exclude) exclude.extend([ct_field.name, fk_field.name]) diff --git a/django/contrib/flatpages/middleware.py b/django/contrib/flatpages/middleware.py index 2f494064f3..9fe595d0cf 100644 --- a/django/contrib/flatpages/middleware.py +++ b/django/contrib/flatpages/middleware.py @@ -6,7 +6,7 @@ from django.conf import settings class FlatpageFallbackMiddleware(object): def process_response(self, request, response): if response.status_code != 404: - return response # No need to check for a flatpage for non-404 responses. + return response # No need to check for a flatpage for non-404 responses. try: return flatpage(request, request.path_info) # Return the original response if any errors happened. Because this diff --git a/django/contrib/formtools/preview.py b/django/contrib/formtools/preview.py index e7de911a8d..02e6f27547 100644 --- a/django/contrib/formtools/preview.py +++ b/django/contrib/formtools/preview.py @@ -8,7 +8,7 @@ from django.template.context import RequestContext from django.utils.crypto import constant_time_compare from django.contrib.formtools.utils import form_hmac -AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter. +AUTO_ID = 'formtools_%s' # Each form here uses this as its auto_id parameter. class FormPreview(object): @@ -42,7 +42,7 @@ class FormPreview(object): try: self.form.base_fields[name] except KeyError: - break # This field name isn't being used by the form. + break # This field name isn't being used by the form. name += '_' return name @@ -75,7 +75,7 @@ class FormPreview(object): if f.is_valid(): if not self._check_security_hash(request.POST.get(self.unused_name('hash'), ''), request, f): - return self.failed_hash(request) # Security hash failed. + return self.failed_hash(request) # Security hash failed. return self.done(request, f.cleaned_data) else: return render_to_response(self.form_template, diff --git a/django/contrib/gis/db/backends/mysql/operations.py b/django/contrib/gis/db/backends/mysql/operations.py index 26cec743a9..81aa1e2fb6 100644 --- a/django/contrib/gis/db/backends/mysql/operations.py +++ b/django/contrib/gis/db/backends/mysql/operations.py @@ -14,11 +14,11 @@ class MySQLOperations(DatabaseOperations, BaseSpatialOperations): from_text = 'GeomFromText' Adapter = WKTAdapter - Adaptor = Adapter # Backwards-compatibility alias. + Adaptor = Adapter # Backwards-compatibility alias. geometry_functions = { - 'bbcontains': 'MBRContains', # For consistency w/PostGIS API - 'bboverlaps': 'MBROverlaps', # .. .. + 'bbcontains': 'MBRContains', # For consistency w/PostGIS API + 'bboverlaps': 'MBROverlaps', # .. .. 'contained': 'MBRWithin', # .. .. 'contains': 'MBRContains', 'disjoint': 'MBRDisjoint', diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py index 14df0ff1d3..8212938f01 100644 --- a/django/contrib/gis/db/backends/oracle/operations.py +++ b/django/contrib/gis/db/backends/oracle/operations.py @@ -86,7 +86,7 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations): valid_aggregates = {'Union', 'Extent'} Adapter = OracleSpatialAdapter - Adaptor = Adapter # Backwards-compatibility alias. + Adaptor = Adapter # Backwards-compatibility alias. area = 'SDO_GEOM.SDO_AREA' gml = 'SDO_UTIL.TO_GMLGEOMETRY' @@ -126,12 +126,12 @@ class OracleOperations(DatabaseOperations, BaseSpatialOperations): 'coveredby': SDOOperation('SDO_COVEREDBY'), 'covers': SDOOperation('SDO_COVERS'), 'disjoint': SDOGeomRelate('DISJOINT'), - 'intersects': SDOOperation('SDO_OVERLAPBDYINTERSECT'), # TODO: Is this really the same as ST_Intersects()? + 'intersects': SDOOperation('SDO_OVERLAPBDYINTERSECT'), # TODO: Is this really the same as ST_Intersects()? 'equals': SDOOperation('SDO_EQUAL'), 'exact': SDOOperation('SDO_EQUAL'), 'overlaps': SDOOperation('SDO_OVERLAPS'), 'same_as': SDOOperation('SDO_EQUAL'), - 'relate': (SDORelate, six.string_types), # Oracle uses a different syntax, e.g., 'mask=inside+touch' + 'relate': (SDORelate, six.string_types), # Oracle uses a different syntax, e.g., 'mask=inside+touch' 'touches': SDOOperation('SDO_TOUCH'), 'within': SDOOperation('SDO_INSIDE'), } diff --git a/django/contrib/gis/db/backends/postgis/operations.py b/django/contrib/gis/db/backends/postgis/operations.py index eae08479df..1a71be681c 100644 --- a/django/contrib/gis/db/backends/postgis/operations.py +++ b/django/contrib/gis/db/backends/postgis/operations.py @@ -79,7 +79,7 @@ class PostGISOperations(DatabaseOperations, BaseSpatialOperations): valid_aggregates = {'Collect', 'Extent', 'Extent3D', 'MakeLine', 'Union'} Adapter = PostGISAdapter - Adaptor = Adapter # Backwards-compatibility alias. + Adaptor = Adapter # Backwards-compatibility alias. def __init__(self, connection): super(PostGISOperations, self).__init__(connection) diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py index 827c5217a5..5149b541a2 100644 --- a/django/contrib/gis/db/backends/spatialite/operations.py +++ b/django/contrib/gis/db/backends/spatialite/operations.py @@ -68,7 +68,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations): valid_aggregates = {'Extent', 'Union'} Adapter = SpatiaLiteAdapter - Adaptor = Adapter # Backwards-compatibility alias. + Adaptor = Adapter # Backwards-compatibility alias. area = 'Area' centroid = 'Centroid' @@ -77,7 +77,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations): distance = 'Distance' envelope = 'Envelope' intersection = 'Intersection' - length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword + length = 'GLength' # OpenGis defines Length, but this conflicts with an SQLite reserved keyword num_geom = 'NumGeometries' num_points = 'NumPoints' point_on_surface = 'PointOnSurface' @@ -86,7 +86,7 @@ class SpatiaLiteOperations(DatabaseOperations, BaseSpatialOperations): sym_difference = 'SymDifference' transform = 'Transform' translate = 'ShiftCoords' - union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword + union = 'GUnion' # OpenGis defines Union, but this conflicts with an SQLite reserved keyword unionagg = 'GUnion' from_text = 'GeomFromText' diff --git a/django/contrib/gis/db/models/fields.py b/django/contrib/gis/db/models/fields.py index 662b20ae79..6dc2ee23b9 100644 --- a/django/contrib/gis/db/models/fields.py +++ b/django/contrib/gis/db/models/fields.py @@ -188,7 +188,7 @@ class GeometryField(Field): the SRID set for the field. For example, if the input geometry has no SRID, then that of the field will be returned. """ - gsrid = geom.srid # SRID of given geometry. + gsrid = geom.srid # SRID of given geometry. if gsrid is None or self.srid == -1 or (gsrid == -1 and self.srid != -1): return self.srid else: diff --git a/django/contrib/gis/db/models/query.py b/django/contrib/gis/db/models/query.py index 5f1d4623ab..cdff5396cc 100644 --- a/django/contrib/gis/db/models/query.py +++ b/django/contrib/gis/db/models/query.py @@ -50,7 +50,7 @@ class GeoQuerySet(QuerySet): if backend.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args']['tolerance'] = tolerance - s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters. + s['select_field'] = AreaField('sq_m') # Oracle returns area in units of meters. elif backend.postgis or backend.spatialite: if backend.geography: # Geography fields support area calculation, returns square meters. @@ -420,7 +420,7 @@ class GeoQuerySet(QuerySet): custom_sel = '%s(%s, %s)' % (connections[self.db].ops.transform, geo_col, srid) # TODO: Should we have this as an alias? # custom_sel = '(%s(%s, %s)) AS %s' % (SpatialBackend.transform, geo_col, srid, qn(geo_field.name)) - self.query.transformed_srid = srid # So other GeoQuerySet methods + self.query.transformed_srid = srid # So other GeoQuerySet methods self.query.custom_select[geo_field] = custom_sel return self._clone() diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py index a331053eeb..753baff9ac 100644 --- a/django/contrib/gis/gdal/geometries.py +++ b/django/contrib/gis/gdal/geometries.py @@ -339,9 +339,9 @@ class OGRGeometry(GDALBase): def wkb(self): "Returns the WKB representation of the Geometry." if sys.byteorder == 'little': - byteorder = 1 # wkbNDR (from ogr_core.h) + byteorder = 1 # wkbNDR (from ogr_core.h) else: - byteorder = 0 # wkbXDR + byteorder = 0 # wkbXDR sz = self.wkb_size # Creating the unsigned character buffer, and passing it in by reference. buf = (c_ubyte * sz)() @@ -635,7 +635,7 @@ class Polygon(OGRGeometry): @property def shell(self): "Returns the shell of this Polygon." - return self[0] # First ring is the shell + return self[0] # First ring is the shell exterior_ring = shell @property diff --git a/django/contrib/gis/gdal/prototypes/ds.py b/django/contrib/gis/gdal/prototypes/ds.py index 11d3b2452f..374a0f424e 100644 --- a/django/contrib/gis/gdal/prototypes/ds.py +++ b/django/contrib/gis/gdal/prototypes/ds.py @@ -9,7 +9,7 @@ from django.contrib.gis.gdal.libgdal import lgdal from django.contrib.gis.gdal.prototypes.generation import (const_string_output, double_output, geom_output, int_output, srs_output, void_output, voidptr_output) -c_int_p = POINTER(c_int) # shortcut type +c_int_p = POINTER(c_int) # shortcut type ### Driver Routines ### register_all = void_output(lgdal.OGRRegisterAll, [], errcheck=False) diff --git a/django/contrib/gis/gdal/prototypes/geom.py b/django/contrib/gis/gdal/prototypes/geom.py index f5dc7e10e9..4e4fb633c7 100644 --- a/django/contrib/gis/gdal/prototypes/geom.py +++ b/django/contrib/gis/gdal/prototypes/geom.py @@ -59,7 +59,7 @@ import_wkt = void_output(lgdal.OGR_G_ImportFromWkt, [c_void_p, POINTER(c_char_p) destroy_geom = void_output(lgdal.OGR_G_DestroyGeometry, [c_void_p], errcheck=False) # Geometry export routines. -to_wkb = void_output(lgdal.OGR_G_ExportToWkb, None, errcheck=True) # special handling for WKB. +to_wkb = void_output(lgdal.OGR_G_ExportToWkb, None, errcheck=True) # special handling for WKB. to_wkt = string_output(lgdal.OGR_G_ExportToWkt, [c_void_p, POINTER(c_char_p)], decoding='ascii') to_gml = string_output(lgdal.OGR_G_ExportToGML, [c_void_p], str_result=True, decoding='ascii') get_wkbsize = int_output(lgdal.OGR_G_WkbSize, [c_void_p]) diff --git a/django/contrib/gis/gdal/tests/test_ds.py b/django/contrib/gis/gdal/tests/test_ds.py index a2c0e9e133..5cfdb4a8ea 100644 --- a/django/contrib/gis/gdal/tests/test_ds.py +++ b/django/contrib/gis/gdal/tests/test_ds.py @@ -13,19 +13,19 @@ if HAS_GDAL: ds_list = ( TestDS('test_point', nfeat=5, nfld=3, geom='POINT', gtype=1, driver='ESRI Shapefile', fields={'dbl': OFTReal, 'int': OFTInteger, 'str': OFTString}, - extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS + extent=(-1.35011, 0.166623, -0.524093, 0.824508), # Got extent from QGIS srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]', field_values={'dbl': [float(i) for i in range(1, 6)], 'int': list(range(1, 6)), 'str': [str(i) for i in range(1, 6)]}, fids=range(5)), TestDS('test_vrt', ext='vrt', nfeat=3, nfld=3, geom='POINT', gtype='Point25D', driver='VRT', - fields={'POINT_X': OFTString, 'POINT_Y': OFTString, 'NUM': OFTString}, # VRT uses CSV, which all types are OFTString. - extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV + fields={'POINT_X': OFTString, 'POINT_Y': OFTString, 'NUM': OFTString}, # VRT uses CSV, which all types are OFTString. + extent=(1.0, 2.0, 100.0, 523.5), # Min/Max from CSV field_values={'POINT_X': ['1.0', '5.0', '100.0'], 'POINT_Y': ['2.0', '23.0', '523.5'], 'NUM': ['5', '17', '23']}, fids=range(1, 4)), TestDS('test_poly', nfeat=3, nfld=3, geom='POLYGON', gtype=3, driver='ESRI Shapefile', fields={'float': OFTReal, 'int': OFTInteger, 'str': OFTString}, - extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS + extent=(-1.01513, -0.558245, 0.161876, 0.839637), # Got extent from QGIS srs_wkt='GEOGCS["GCS_WGS_1984",DATUM["WGS_1984",SPHEROID["WGS_1984",6378137,298.257223563]],PRIMEM["Greenwich",0],UNIT["Degree",0.017453292519943295]]'), ) diff --git a/django/contrib/gis/gdal/tests/test_envelope.py b/django/contrib/gis/gdal/tests/test_envelope.py index 4644fbc533..555ca69531 100644 --- a/django/contrib/gis/gdal/tests/test_envelope.py +++ b/django/contrib/gis/gdal/tests/test_envelope.py @@ -23,7 +23,7 @@ class EnvelopeTest(unittest.TestCase): "Testing Envelope initilization." e1 = Envelope((0, 0, 5, 5)) Envelope(0, 0, 5, 5) - Envelope(0, '0', '5', 5) # Thanks to ww for this + Envelope(0, '0', '5', 5) # Thanks to ww for this Envelope(e1._envelope) self.assertRaises(OGRException, Envelope, (5, 5, 0, 0)) self.assertRaises(OGRException, Envelope, 5, 5, 0, 0) diff --git a/django/contrib/gis/gdal/tests/test_geom.py b/django/contrib/gis/gdal/tests/test_geom.py index 65d78a1735..ed6bb2ad9c 100644 --- a/django/contrib/gis/gdal/tests/test_geom.py +++ b/django/contrib/gis/gdal/tests/test_geom.py @@ -130,7 +130,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): OGRGeometry('POINT(0 0)') for p in self.geometries.points: - if not hasattr(p, 'z'): # No 3D + if not hasattr(p, 'z'): # No 3D pnt = OGRGeometry(p.wkt) self.assertEqual(1, pnt.geom_type) self.assertEqual('POINT', pnt.geom_name) @@ -141,15 +141,15 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): def test03_multipoints(self): "Testing MultiPoint objects." for mp in self.geometries.multipoints: - mgeom1 = OGRGeometry(mp.wkt) # First one from WKT + mgeom1 = OGRGeometry(mp.wkt) # First one from WKT self.assertEqual(4, mgeom1.geom_type) self.assertEqual('MULTIPOINT', mgeom1.geom_name) - mgeom2 = OGRGeometry('MULTIPOINT') # Creating empty multipoint + mgeom2 = OGRGeometry('MULTIPOINT') # Creating empty multipoint mgeom3 = OGRGeometry('MULTIPOINT') for g in mgeom1: - mgeom2.add(g) # adding each point from the multipoints - mgeom3.add(g.wkt) # should take WKT as well - self.assertEqual(mgeom1, mgeom2) # they should equal + mgeom2.add(g) # adding each point from the multipoints + mgeom3.add(g.wkt) # should take WKT as well + self.assertEqual(mgeom1, mgeom2) # they should equal self.assertEqual(mgeom1, mgeom3) self.assertEqual(mp.coords, mgeom2.coords) self.assertEqual(mp.n_p, mgeom2.point_count) @@ -247,7 +247,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): poly.centroid poly.close_rings() - self.assertEqual(10, poly.point_count) # Two closing points should've been added + self.assertEqual(10, poly.point_count) # Two closing points should've been added self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid) def test08_multipolygons(self): @@ -309,7 +309,7 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): # Changing each ring in the polygon self.assertEqual(32140, ring.srs.srid) self.assertEqual('NAD83 / Texas South Central', ring.srs.name) - ring.srs = str(SpatialReference(4326)) # back to WGS84 + ring.srs = str(SpatialReference(4326)) # back to WGS84 self.assertEqual(4326, ring.srs.srid) # Using the `srid` property. @@ -361,8 +361,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertEqual(d1, d2) - self.assertEqual(d1, a - b) # __sub__ is difference operator - a -= b # testing __isub__ + self.assertEqual(d1, a - b) # __sub__ is difference operator + a -= b # testing __isub__ self.assertEqual(d1, a) def test11_intersection(self): @@ -374,8 +374,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): self.assertTrue(a.intersects(b)) i2 = a.intersection(b) self.assertEqual(i1, i2) - self.assertEqual(i1, a & b) # __and__ is intersection operator - a &= b # testing __iand__ + self.assertEqual(i1, a & b) # __and__ is intersection operator + a &= b # testing __iand__ self.assertEqual(i1, a) def test12_symdifference(self): @@ -386,8 +386,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertEqual(d1, d2) - self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator - a ^= b # testing __ixor__ + self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator + a ^= b # testing __ixor__ self.assertEqual(d1, a) def test13_union(self): @@ -398,8 +398,8 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): u1 = OGRGeometry(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertEqual(u1, u2) - self.assertEqual(u1, a | b) # __or__ is union operator - a |= b # testing __ior__ + self.assertEqual(u1, a | b) # __or__ is union operator + a |= b # testing __ior__ self.assertEqual(u1, a) def test14_add(self): @@ -418,9 +418,9 @@ class OGRGeomTest(unittest.TestCase, TestDataMixin): mp3 = OGRGeometry('MultiPolygon') for poly in mpoly: - mp1.add(poly) # Adding a geometry at a time - mp2.add(poly.wkt) # Adding WKT - mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once. + mp1.add(poly) # Adding a geometry at a time + mp2.add(poly.wkt) # Adding WKT + mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once. for tmp in (mp1, mp2, mp3): self.assertEqual(mpoly, tmp) diff --git a/django/contrib/gis/gdal/tests/test_srs.py b/django/contrib/gis/gdal/tests/test_srs.py index 39cccf8440..372232755d 100644 --- a/django/contrib/gis/gdal/tests/test_srs.py +++ b/django/contrib/gis/gdal/tests/test_srs.py @@ -127,8 +127,8 @@ class SpatialRefTest(unittest.TestCase): for s in srlist: srs = SpatialReference(s.wkt) for tup in s.attr: - att = tup[0] # Attribute to test - exp = tup[1] # Expected result + att = tup[0] # Attribute to test + exp = tup[1] # Expected result self.assertEqual(exp, srs[att]) def test11_wellknown(self): diff --git a/django/contrib/gis/geoip/tests.py b/django/contrib/gis/geoip/tests.py index 4e7a990d50..f771608e1d 100644 --- a/django/contrib/gis/geoip/tests.py +++ b/django/contrib/gis/geoip/tests.py @@ -30,10 +30,10 @@ class GeoIPTest(unittest.TestCase): def test01_init(self): "Testing GeoIP initialization." - g1 = GeoIP() # Everything inferred from GeoIP path + g1 = GeoIP() # Everything inferred from GeoIP path path = settings.GEOIP_PATH - g2 = GeoIP(path, 0) # Passing in data path explicitly. - g3 = GeoIP.open(path, 0) # MaxMind Python API syntax. + g2 = GeoIP(path, 0) # Passing in data path explicitly. + g3 = GeoIP.open(path, 0) # MaxMind Python API syntax. for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) diff --git a/django/contrib/gis/geos/linestring.py b/django/contrib/gis/geos/linestring.py index 7a03712600..72f766310e 100644 --- a/django/contrib/gis/geos/linestring.py +++ b/django/contrib/gis/geos/linestring.py @@ -47,7 +47,7 @@ class LineString(GEOSGeometry): raise TypeError('Dimension mismatch.') numpy_coords = False elif numpy and isinstance(coords, numpy.ndarray): - shape = coords.shape # Using numpy's shape. + shape = coords.shape # Using numpy's shape. if len(shape) != 2: raise TypeError('Too many dimensions.') self._checkdim(shape[1]) @@ -91,8 +91,8 @@ class LineString(GEOSGeometry): _get_single_internal = _get_single_external def _set_list(self, length, items): - ndim = self._cs.dims # - hasz = self._cs.hasz # I don't understand why these are different + ndim = self._cs.dims + hasz = self._cs.hasz # I don't understand why these are different # create a new coordinate sequence and populate accordingly cs = GEOSCoordSeq(capi.create_cs(length, ndim), z=hasz) @@ -130,7 +130,7 @@ class LineString(GEOSGeometry): """ lst = [func(i) for i in xrange(len(self))] if numpy: - return numpy.array(lst) # ARRRR! + return numpy.array(lst) # ARRRR! else: return lst diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py index bd99047604..a3682ffd91 100644 --- a/django/contrib/gis/geos/prototypes/errcheck.py +++ b/django/contrib/gis/geos/prototypes/errcheck.py @@ -58,7 +58,7 @@ def check_minus_one(result, func, cargs): def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." - val = ord(result) # getting the ordinal from the character + val = ord(result) # getting the ordinal from the character if val == 1: return True elif val == 0: diff --git a/django/contrib/gis/geos/prototypes/misc.py b/django/contrib/gis/geos/prototypes/misc.py index 55381bf7fd..6b10396aba 100644 --- a/django/contrib/gis/geos/prototypes/misc.py +++ b/django/contrib/gis/geos/prototypes/misc.py @@ -21,7 +21,7 @@ def dbl_from_geom(func, num_geom=1): argtypes = [GEOM_PTR for i in xrange(num_geom)] argtypes += [POINTER(c_double)] func.argtypes = argtypes - func.restype = c_int # Status code returned + func.restype = c_int # Status code returned func.errcheck = check_dbl return func diff --git a/django/contrib/gis/geos/tests/test_geos.py b/django/contrib/gis/geos/tests/test_geos.py index 9c24f614df..59cd9a32cc 100644 --- a/django/contrib/gis/geos/tests/test_geos.py +++ b/django/contrib/gis/geos/tests/test_geos.py @@ -198,7 +198,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): poly = fromstr(ewkt) self.assertEqual(srid, poly.srid) self.assertEqual(srid, poly.shell.srid) - self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export + self.assertEqual(srid, fromstr(poly.ewkt).srid) # Checking export @skipUnless(HAS_GDAL, "GDAL is required.") def test_json(self): @@ -279,7 +279,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # Now testing the different constructors pnt2 = Point(tup_args) # e.g., Point((1, 2)) - pnt3 = Point(*tup_args) # e.g., Point(1, 2) + pnt3 = Point(*tup_args) # e.g., Point(1, 2) self.assertEqual(True, pnt == pnt2) self.assertEqual(True, pnt == pnt3) @@ -295,7 +295,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): pnt.coords = set_tup2 self.assertEqual(set_tup2, pnt.coords) - prev = pnt # setting the previous geometry + prev = pnt # setting the previous geometry def test_multipoints(self): "Testing MultiPoint objects." @@ -337,11 +337,11 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # Creating a LineString from a tuple, list, and numpy array self.assertEqual(ls, LineString(ls.tuple)) # tuple - self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments - self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list - self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments + self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments + self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list + self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments if numpy: - self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array + self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array def test_multilinestring(self): "Testing MultiLineString objects." @@ -409,7 +409,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): self.assertEqual(poly.empty, False) self.assertEqual(poly.ring, False) self.assertEqual(p.n_i, poly.num_interior_rings) - self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ + self.assertEqual(p.n_i + 1, len(poly)) # Testing __len__ self.assertEqual(p.n_p, poly.num_points) # Area & Centroid @@ -419,7 +419,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # Testing the geometry equivalence self.assertEqual(True, poly == fromstr(p.wkt)) - self.assertEqual(False, poly == prev) # Should not be equal to previous geometry + self.assertEqual(False, poly == prev) # Should not be equal to previous geometry self.assertEqual(True, poly != prev) # Testing the exterior ring @@ -428,7 +428,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): self.assertEqual(ring.geom_typeid, 2) if p.ext_ring_cs: self.assertEqual(p.ext_ring_cs, ring.tuple) - self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ + self.assertEqual(p.ext_ring_cs, poly[0].tuple) # Testing __getitem__ # Testing __getitem__ and __setitem__ on invalid indices self.assertRaises(GEOSIndexError, poly.__getitem__, len(poly)) @@ -522,13 +522,13 @@ class GEOSTest(unittest.TestCase, TestDataMixin): poly = fromstr(p.wkt) cs = poly.exterior_ring.coord_seq - self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too. - self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works + self.assertEqual(p.ext_ring_cs, cs.tuple) # done in the Polygon test too. + self.assertEqual(len(p.ext_ring_cs), len(cs)) # Making sure __len__ works # Checks __getitem__ and __setitem__ for i in xrange(len(p.ext_ring_cs)): - c1 = p.ext_ring_cs[i] # Expected value - c2 = cs[i] # Value from coordseq + c1 = p.ext_ring_cs[i] # Expected value + c2 = cs[i] # Value from coordseq self.assertEqual(c1, c2) # Constructing the test value to set the coordinate sequence with @@ -562,8 +562,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin): self.assertEqual(True, a.intersects(b)) i2 = a.intersection(b) self.assertEqual(i1, i2) - self.assertEqual(i1, a & b) # __and__ is intersection operator - a &= b # testing __iand__ + self.assertEqual(i1, a & b) # __and__ is intersection operator + a &= b # testing __iand__ self.assertEqual(i1, a) def test_union(self): @@ -574,8 +574,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin): u1 = fromstr(self.geometries.union_geoms[i].wkt) u2 = a.union(b) self.assertEqual(u1, u2) - self.assertEqual(u1, a | b) # __or__ is union operator - a |= b # testing __ior__ + self.assertEqual(u1, a | b) # __or__ is union operator + a |= b # testing __ior__ self.assertEqual(u1, a) def test_difference(self): @@ -586,8 +586,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin): d1 = fromstr(self.geometries.diff_geoms[i].wkt) d2 = a.difference(b) self.assertEqual(d1, d2) - self.assertEqual(d1, a - b) # __sub__ is difference operator - a -= b # testing __isub__ + self.assertEqual(d1, a - b) # __sub__ is difference operator + a -= b # testing __isub__ self.assertEqual(d1, a) def test_symdifference(self): @@ -598,8 +598,8 @@ class GEOSTest(unittest.TestCase, TestDataMixin): d1 = fromstr(self.geometries.sdiff_geoms[i].wkt) d2 = a.sym_difference(b) self.assertEqual(d1, d2) - self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator - a ^= b # testing __ixor__ + self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator + a ^= b # testing __ixor__ self.assertEqual(d1, a) def test_buffer(self): @@ -667,7 +667,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): p2 = fromstr(p1.hex) self.assertEqual(exp_srid, p2.srid) - p3 = fromstr(p1.hex, srid=-1) # -1 is intended. + p3 = fromstr(p1.hex, srid=-1) # -1 is intended. self.assertEqual(-1, p3.srid) @skipUnless(HAS_GDAL, "GDAL is required.") @@ -705,7 +705,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # Assigning polygon's exterior ring w/the new shell poly.exterior_ring = new_shell - str(new_shell) # new shell is still accessible + str(new_shell) # new shell is still accessible self.assertEqual(poly.exterior_ring, new_shell) self.assertEqual(poly[0], new_shell) @@ -718,7 +718,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): new = Point(random.randint(21, 100), random.randint(21, 100)) # Testing the assignment mp[i] = new - str(new) # what was used for the assignment is still accessible + str(new) # what was used for the assignment is still accessible self.assertEqual(mp[i], new) self.assertEqual(mp[i].wkt, new.wkt) self.assertNotEqual(pnt, mp[i]) @@ -740,7 +740,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): self.assertNotEqual(mpoly[i], poly) # Testing the assignment mpoly[i] = poly - str(poly) # Still accessible + str(poly) # Still accessible self.assertEqual(mpoly[i], poly) self.assertNotEqual(mpoly[i], old_poly) @@ -821,7 +821,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # Testing len() and num_geom. if isinstance(g, Polygon): - self.assertEqual(1, len(g)) # Has one empty linear ring + self.assertEqual(1, len(g)) # Has one empty linear ring self.assertEqual(1, g.num_geom) self.assertEqual(0, len(g[0])) elif isinstance(g, (Point, LineString)): @@ -1039,7 +1039,7 @@ class GEOSTest(unittest.TestCase, TestDataMixin): # A set of test points. pnts = [Point(5, 5), Point(7.5, 7.5), Point(2.5, 7.5)] - covers = [True, True, False] # No `covers` op for regular GEOS geoms. + covers = [True, True, False] # No `covers` op for regular GEOS geoms. for pnt, c in zip(pnts, covers): # Results should be the same (but faster) self.assertEqual(mpoly.contains(pnt), prep.contains(pnt)) diff --git a/django/contrib/gis/geos/tests/test_mutable_list.py b/django/contrib/gis/geos/tests/test_mutable_list.py index fc3b247f1f..5340dac99d 100644 --- a/django/contrib/gis/geos/tests/test_mutable_list.py +++ b/django/contrib/gis/geos/tests/test_mutable_list.py @@ -223,9 +223,9 @@ class ListMixinTest(unittest.TestCase): del x[i] pl, ul = self.lists_of_len() for i in (-1 - self.limit, self.limit): - self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i) - self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i) - self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i) + self.assertRaises(IndexError, setfcn, ul, i) # 'set index %d' % i) + self.assertRaises(IndexError, getfcn, ul, i) # 'get index %d' % i) + self.assertRaises(IndexError, delfcn, ul, i) # 'del index %d' % i) def test06_list_methods(self): 'List methods' diff --git a/django/contrib/gis/maps/google/gmap.py b/django/contrib/gis/maps/google/gmap.py index ee820fc3c6..b61c95913d 100644 --- a/django/contrib/gis/maps/google/gmap.py +++ b/django/contrib/gis/maps/google/gmap.py @@ -20,9 +20,9 @@ class GoogleMap(object): "A class for generating Google Maps JavaScript." # String constants - onunload = mark_safe('onunload="GUnload()"') # Cleans up after Google Maps - vml_css = mark_safe('v\:* {behavior:url(#default#VML);}') # CSS for IE VML - xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"') # XML Namespace (for IE VML). + onunload = mark_safe('onunload="GUnload()"') # Cleans up after Google Maps + vml_css = mark_safe('v\:* {behavior:url(#default#VML);}') # CSS for IE VML + xmlns = mark_safe('xmlns:v="urn:schemas-microsoft-com:vml"') # XML Namespace (for IE VML). def __init__(self, key=None, api_url=None, version=None, center=None, zoom=None, dom_id='map', diff --git a/django/contrib/gis/maps/google/zoom.py b/django/contrib/gis/maps/google/zoom.py index 6bbadcdf16..22b3ceac1d 100644 --- a/django/contrib/gis/maps/google/zoom.py +++ b/django/contrib/gis/maps/google/zoom.py @@ -33,18 +33,18 @@ class GoogleZoom(object): # Initializing arrays to hold the parameters for each one of the # zoom levels. - self._degpp = [] # Degrees per pixel - self._radpp = [] # Radians per pixel - self._npix = [] # 1/2 the number of pixels for a tile at the given zoom level + self._degpp = [] # Degrees per pixel + self._radpp = [] # Radians per pixel + self._npix = [] # 1/2 the number of pixels for a tile at the given zoom level # Incrementing through the zoom levels and populating the parameter arrays. - z = tilesize # The number of pixels per zoom level. + z = tilesize # The number of pixels per zoom level. for i in xrange(num_zoom): # Getting the degrees and radians per pixel, and the 1/2 the number of # for every zoom level. - self._degpp.append(z / 360.) # degrees per pixel - self._radpp.append(z / (2 * pi)) # radians per pixel - self._npix.append(z / 2) # number of pixels to center of tile + self._degpp.append(z / 360.) # degrees per pixel + self._radpp.append(z / (2 * pi)) # radians per pixel + self._npix.append(z / 2) # number of pixels to center of tile # Multiplying `z` by 2 for the next iteration. z *= 2 diff --git a/django/contrib/gis/tests/distapp/tests.py b/django/contrib/gis/tests/distapp/tests.py index 8db977e025..6b7c734066 100644 --- a/django/contrib/gis/tests/distapp/tests.py +++ b/django/contrib/gis/tests/distapp/tests.py @@ -5,7 +5,7 @@ from unittest import skipUnless from django.db import connection from django.db.models import Q from django.contrib.gis.geos import HAS_GEOS -from django.contrib.gis.measure import D # alias for Distance +from django.contrib.gis.measure import D # alias for Distance from django.contrib.gis.tests.utils import ( HAS_SPATIAL_DB, mysql, oracle, postgis, spatialite, no_oracle, no_spatialite ) @@ -123,7 +123,7 @@ class DistanceTest(TestCase): if spatialite or oracle: dist_qs = [dist1, dist2] else: - dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt) # Using EWKT string parameter. + dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt) # Using EWKT string parameter. dist4 = SouthTexasCityFt.objects.distance(lagrange) dist_qs = [dist1, dist2, dist3, dist4] @@ -199,7 +199,7 @@ class DistanceTest(TestCase): for i, c in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol) - @no_oracle # Oracle already handles geographic distance calculation. + @no_oracle # Oracle already handles geographic distance calculation. def test_distance_transform(self): """ Test the `distance` GeoQuerySet method used with `transform` on a geographic field. @@ -307,7 +307,7 @@ class DistanceTest(TestCase): # Cities that are either really close or really far from Wollongong -- # and using different units of distance. wollongong = AustraliaCity.objects.get(name='Wollongong') - d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles. + d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS. gq1 = Q(point__distance_lte=(wollongong.point, d1)) diff --git a/django/contrib/gis/tests/geoapp/models.py b/django/contrib/gis/tests/geoapp/models.py index 251173e432..8234bc8d9b 100644 --- a/django/contrib/gis/tests/geoapp/models.py +++ b/django/contrib/gis/tests/geoapp/models.py @@ -9,7 +9,7 @@ null_flag = not mysql @python_2_unicode_compatible class Country(models.Model): name = models.CharField(max_length=30) - mpoly = models.MultiPolygonField() # SRID, by default, is 4326 + mpoly = models.MultiPolygonField() # SRID, by default, is 4326 objects = models.GeoManager() def __str__(self): @@ -30,13 +30,13 @@ class City(models.Model): class PennsylvaniaCity(City): county = models.CharField(max_length=30) founded = models.DateTimeField(null=True) - objects = models.GeoManager() # TODO: This should be implicitly inherited. + objects = models.GeoManager() # TODO: This should be implicitly inherited. @python_2_unicode_compatible class State(models.Model): name = models.CharField(max_length=30) - poly = models.PolygonField(null=null_flag) # Allowing NULL geometries here. + poly = models.PolygonField(null=null_flag) # Allowing NULL geometries here. objects = models.GeoManager() def __str__(self): @@ -68,5 +68,5 @@ if not spatialite: return self.name class MinusOneSRID(models.Model): - geom = models.PointField(srid=-1) # Minus one SRID. + geom = models.PointField(srid=-1) # Minus one SRID. objects = models.GeoManager() diff --git a/django/contrib/gis/tests/geoapp/test_feeds.py b/django/contrib/gis/tests/geoapp/test_feeds.py index 9ae06d76e0..7b8fc159b4 100644 --- a/django/contrib/gis/tests/geoapp/test_feeds.py +++ b/django/contrib/gis/tests/geoapp/test_feeds.py @@ -92,5 +92,5 @@ class GeoFeedTest(TestCase): self.assertChildNodes(item, ['title', 'link', 'description', 'guid', 'geo:lat', 'geo:lon']) # Boxes and Polygons aren't allowed in W3C Geo feeds. - self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in - self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in + self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo2/') # Box in + self.assertRaises(ValueError, self.client.get, '/feeds/w3cgeo3/') # Polygons in diff --git a/django/contrib/gis/tests/geoapp/test_sitemaps.py b/django/contrib/gis/tests/geoapp/test_sitemaps.py index 92d70e1fd5..d9ede80c57 100644 --- a/django/contrib/gis/tests/geoapp/test_sitemaps.py +++ b/django/contrib/gis/tests/geoapp/test_sitemaps.py @@ -59,7 +59,7 @@ class GeoSitemapTest(TestCase): self.assertEqual(urlset.getAttribute('xmlns:geo'), 'http://www.google.com/geo/schemas/sitemap/1.0') urls = urlset.getElementsByTagName('url') - self.assertEqual(2, len(urls)) # Should only be 2 sitemaps. + self.assertEqual(2, len(urls)) # Should only be 2 sitemaps. for url in urls: self.assertChildNodes(url, ['loc', 'geo:geo']) # Making sure the 'geo:format' element was properly set. diff --git a/django/contrib/gis/tests/geoapp/tests.py b/django/contrib/gis/tests/geoapp/tests.py index 4b20c4b2c8..f1b2f1adbe 100644 --- a/django/contrib/gis/tests/geoapp/tests.py +++ b/django/contrib/gis/tests/geoapp/tests.py @@ -84,7 +84,7 @@ class GeoModelTest(TestCase): # Creating a State object using a built Polygon ply = Polygon(shell, inner) nullstate = State(name='NullState', poly=ply) - self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None + self.assertEqual(4326, nullstate.poly.srid) # SRID auto-set from None nullstate.save() ns = State.objects.get(name='NullState') @@ -111,7 +111,7 @@ class GeoModelTest(TestCase): "Testing automatic transform for lookups and inserts." # San Antonio in 'WGS84' (SRID 4326) sa_4326 = 'POINT (-98.493183 29.424170)' - wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 + wgs_pnt = fromstr(sa_4326, srid=4326) # Our reference point in WGS84 # Oracle doesn't have SRID 3084, using 41157. if oracle: @@ -122,7 +122,7 @@ class GeoModelTest(TestCase): nad_srid = 41157 else: # San Antonio in 'NAD83(HARN) / Texas Centric Lambert Conformal' (SRID 3084) - nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform + nad_wkt = 'POINT (1645978.362408288754523 6276356.025927528738976)' # Used ogr.py in gdal 1.4.1 for this transform nad_srid = 3084 # Constructing & querying with a point from a different SRID. Oracle @@ -156,7 +156,7 @@ class GeoModelTest(TestCase): c = City() self.assertEqual(c.point, None) - @no_spatialite # SpatiaLite does not support abstract geometry columns + @no_spatialite # SpatiaLite does not support abstract geometry columns def test_geometryfield(self): "Testing the general GeometryField." Feature(name='Point', geom=Point(1, 1)).save() @@ -242,8 +242,8 @@ class GeoLookupTest(TestCase): # Now testing contains on the countries using the points for # Houston and Wellington. - tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry - nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX + tx = Country.objects.get(mpoly__contains=houston.point) # Query w/GEOSGeometry + nz = Country.objects.get(mpoly__contains=wellington.point.hex) # Query w/EWKBHEX self.assertEqual('Texas', tx.name) self.assertEqual('New Zealand', nz.name) @@ -254,9 +254,9 @@ class GeoLookupTest(TestCase): # Pueblo and Oklahoma City (even though OK City is within the bounding box of Texas) # are not contained in Texas or New Zealand. - self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point))) # Query w/GEOSGeometry object + self.assertEqual(0, len(Country.objects.filter(mpoly__contains=pueblo.point))) # Query w/GEOSGeometry object self.assertEqual((mysql and 1) or 0, - len(Country.objects.filter(mpoly__contains=okcity.point.wkt))) # Qeury w/WKT + len(Country.objects.filter(mpoly__contains=okcity.point.wkt))) # Qeury w/WKT # OK City is contained w/in bounding box of Texas. if not oracle: @@ -446,7 +446,7 @@ class GeoQuerySetTest(TestCase): self.assertIsInstance(country.envelope, Polygon) @no_mysql - @no_spatialite # SpatiaLite does not have an Extent function + @no_spatialite # SpatiaLite does not have an Extent function def test_extent(self): "Testing the `extent` GeoQuerySet method." # Reference query: @@ -618,7 +618,7 @@ class GeoQuerySetTest(TestCase): self.assertEqual(1, c.num_geom) @no_mysql - @no_spatialite # SpatiaLite can only count vertices in LineStrings + @no_spatialite # SpatiaLite can only count vertices in LineStrings def test_num_points(self): "Testing the `num_points` GeoQuerySet method." for c in Country.objects.num_points(): @@ -671,7 +671,7 @@ class GeoQuerySetTest(TestCase): def test_scale(self): "Testing the `scale` GeoQuerySet method." xfac, yfac = 2, 3 - tol = 5 # XXX The low precision tolerance is for SpatiaLite + tol = 5 # XXX The low precision tolerance is for SpatiaLite qs = Country.objects.scale(xfac, yfac, model_att='scaled') for c in qs: for p1, p2 in zip(c.mpoly, c.scaled): @@ -740,7 +740,7 @@ class GeoQuerySetTest(TestCase): # Pre-transformed points for Houston and Pueblo. htown = fromstr('POINT(1947516.83115183 6322297.06040572)', srid=3084) ptown = fromstr('POINT(992363.390841912 481455.395105533)', srid=2774) - prec = 3 # Precision is low due to version variations in PROJ and GDAL. + prec = 3 # Precision is low due to version variations in PROJ and GDAL. # Asserting the result of the transform operation with the values in # the pre-transformed points. Oracle does not have the 3084 SRID. diff --git a/django/contrib/gis/tests/geogapp/tests.py b/django/contrib/gis/tests/geogapp/tests.py index 83c73dfd4d..615c142324 100644 --- a/django/contrib/gis/tests/geogapp/tests.py +++ b/django/contrib/gis/tests/geogapp/tests.py @@ -48,7 +48,7 @@ class GeographyTest(TestCase): "Ensuring exceptions are raised for operators & functions invalid on geography fields." # Only a subset of the geometry functions & operator are available # to PostGIS geography types. For more information, visit: - # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions + # http://postgis.refractions.net/documentation/manual-1.5/ch08.html#PostGIS_GeographyFunctions z = Zipcode.objects.get(code='77002') # ST_Within not available. self.assertRaises(ValueError, City.objects.filter(point__within=z.poly).count) @@ -76,7 +76,7 @@ class GeographyTest(TestCase): # Reference county names, number of polygons, and state names. names = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] - num_polys = [1, 2, 1, 19, 1] # Number of polygons for each. + num_polys = [1, 2, 1, 19, 1] # Number of polygons for each. st_names = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269, unique='name') diff --git a/django/contrib/gis/tests/layermap/models.py b/django/contrib/gis/tests/layermap/models.py index 5e8b0879ed..1b66c6d94c 100644 --- a/django/contrib/gis/tests/layermap/models.py +++ b/django/contrib/gis/tests/layermap/models.py @@ -9,7 +9,7 @@ class State(models.Model): class County(models.Model): name = models.CharField(max_length=25) state = models.ForeignKey(State) - mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83 + mpoly = models.MultiPolygonField(srid=4269) # Multipolygon in NAD83 objects = models.GeoManager() @@ -58,8 +58,8 @@ class Invalid(models.Model): # Mapping dictionaries for the models above. co_mapping = {'name': 'Name', - 'state': {'name': 'State'}, # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case). - 'mpoly': 'MULTIPOLYGON', # Will convert POLYGON features into MULTIPOLYGONS. + 'state': {'name': 'State'}, # ForeignKey's use another mapping dictionary for the _related_ Model (State in this case). + 'mpoly': 'MULTIPOLYGON', # Will convert POLYGON features into MULTIPOLYGONS. } cofeat_mapping = {'name': 'Name', diff --git a/django/contrib/gis/tests/layermap/tests.py b/django/contrib/gis/tests/layermap/tests.py index d42fe1d6ee..df6f22c38a 100644 --- a/django/contrib/gis/tests/layermap/tests.py +++ b/django/contrib/gis/tests/layermap/tests.py @@ -32,7 +32,7 @@ invalid_shp = os.path.join(shp_path, 'invalid', 'emptypoints.shp') # Dictionaries to hold what's expected in the county shapefile. NAMES = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] -NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. +NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. STATES = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] @@ -129,7 +129,7 @@ class LayerMapTest(TestCase): # Should only be one record b/c of `unique` keyword. c = County.objects.get(name=name) self.assertEqual(n, len(c.mpoly)) - self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. + self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. # Multiple records because `unique` was not set. if county_feat: @@ -224,7 +224,7 @@ class LayerMapTest(TestCase): self.assertRaises(TypeError, lm.save, fid_range=bad) # Step keyword should not be allowed w/`fid_range`. - fr = (3, 5) # layer[3:5] + fr = (3, 5) # layer[3:5] self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10) lm.save(fid_range=fr) @@ -237,8 +237,8 @@ class LayerMapTest(TestCase): # Features IDs 5 and beyond for Honolulu County, Hawaii, and # FID 0 is for Pueblo County, Colorado. clear_counties() - lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] - lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] + lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] + lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] # Only Pueblo & Honolulu counties should be present because of # the `unique` keyword. Have to set `order_by` on this QuerySet diff --git a/django/contrib/gis/tests/test_spatialrefsys.py b/django/contrib/gis/tests/test_spatialrefsys.py index 8bc9177fb4..194578d1e0 100644 --- a/django/contrib/gis/tests/test_spatialrefsys.py +++ b/django/contrib/gis/tests/test_spatialrefsys.py @@ -15,7 +15,7 @@ test_srs = ({'srid': 4326, 'proj4_re': r'\+proj=longlat (\+ellps=WGS84 )?\+datum=WGS84 \+no_defs ', 'spheroid': 'WGS 84', 'name': 'WGS 84', 'geographic': True, 'projected': False, 'spatialite': True, - 'ellipsoid': (6378137.0, 6356752.3, 298.257223563), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) + 'ellipsoid': (6378137.0, 6356752.3, 298.257223563), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) 'eprec': (1, 1, 9), }, {'srid': 32140, @@ -27,7 +27,7 @@ test_srs = ({'srid': 4326, r'(\+datum=NAD83 |\+towgs84=0,0,0,0,0,0,0 )?\+units=m \+no_defs ', 'spheroid': 'GRS 1980', 'name': 'NAD83 / Texas South Central', 'geographic': False, 'projected': True, 'spatialite': False, - 'ellipsoid': (6378137.0, 6356752.31414, 298.257222101), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) + 'ellipsoid': (6378137.0, 6356752.31414, 298.257222101), # From proj's "cs2cs -le" and Wikipedia (semi-minor only) 'eprec': (1, 5, 10), }, ) diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index 9d70026dbb..5f57bc1749 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -129,7 +129,7 @@ class LayerMapping(object): if unique: self.check_unique(unique) - transaction_mode = 'autocommit' # Has to be set to autocommit. + transaction_mode = 'autocommit' # Has to be set to autocommit. self.unique = unique else: self.unique = None @@ -286,7 +286,7 @@ class LayerMapping(object): else: raise TypeError('Unique keyword argument must be set with a tuple, list, or string.') - #### Keyword argument retrieval routines #### + # Keyword argument retrieval routines #### def feature_kwargs(self, feat): """ Given an OGR Feature, this will return a dictionary of keyword arguments @@ -359,7 +359,7 @@ class LayerMapping(object): # Getting the decimal value as a tuple. dtup = d.as_tuple() digits = dtup[1] - d_idx = dtup[2] # index where the decimal is + d_idx = dtup[2] # index where the decimal is # Maximum amount of precision, or digits to the left of the decimal. max_prec = model_field.max_digits - model_field.decimal_places diff --git a/django/contrib/messages/storage/cookie.py b/django/contrib/messages/storage/cookie.py index 2ec3fe484b..d0d09dee48 100644 --- a/django/contrib/messages/storage/cookie.py +++ b/django/contrib/messages/storage/cookie.py @@ -101,7 +101,7 @@ class CookieStorage(BaseStorage): if self.max_cookie_size: # data is going to be stored eventually by SimpleCookie, which # adds it's own overhead, which we must account for. - cookie = SimpleCookie() # create outside the loop + cookie = SimpleCookie() # create outside the loop def stored_length(val): return len(cookie.value_encode(val)[1]) diff --git a/django/contrib/messages/tests/test_cookie.py b/django/contrib/messages/tests/test_cookie.py index c4e2b0abfb..028f01382b 100644 --- a/django/contrib/messages/tests/test_cookie.py +++ b/django/contrib/messages/tests/test_cookie.py @@ -77,7 +77,7 @@ class CookieTest(BaseTests, TestCase): response = self.get_response() storage.add(constants.INFO, 'test') for m in storage: - pass # Iterate through the storage to simulate consumption of messages. + pass # Iterate through the storage to simulate consumption of messages. storage.update(response) self.assertEqual(response.cookies['messages'].value, '') self.assertEqual(response.cookies['messages']['domain'], '.example.com') diff --git a/django/contrib/sessions/models.py b/django/contrib/sessions/models.py index 3a6e31152f..1ab42c03e1 100644 --- a/django/contrib/sessions/models.py +++ b/django/contrib/sessions/models.py @@ -14,7 +14,7 @@ class SessionManager(models.Manager): if session_dict: s.save() else: - s.delete() # Clear sessions with no data. + s.delete() # Clear sessions with no data. return s diff --git a/django/contrib/sessions/tests.py b/django/contrib/sessions/tests.py index 275eba5713..862bdfb69b 100644 --- a/django/contrib/sessions/tests.py +++ b/django/contrib/sessions/tests.py @@ -388,7 +388,7 @@ class CacheDBSessionTests(SessionTestsMixin, TestCase): @override_settings(SESSION_CACHE_ALIAS='sessions') def test_non_default_cache(self): - #21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. + # 21000 - CacheDB backend should respect SESSION_CACHE_ALIAS. self.assertRaises(InvalidCacheBackendError, self.backend) diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py index 9b2c5e8bd1..c49c20e59b 100644 --- a/django/core/cache/backends/memcached.py +++ b/django/core/cache/backends/memcached.py @@ -60,7 +60,7 @@ class BaseMemcachedCache(six.with_metaclass(BaseMemcachedCacheMethods, BaseCache # in memcache backends, a negative timeout must be passed. timeout = -1 - if timeout > 2592000: # 60*60*24*30, 30 days + if timeout > 2592000: # 60*60*24*30, 30 days # See http://code.google.com/p/memcached/wiki/FAQ # "You can set expire times up to 30 days in the future. After that # memcached interprets it as a date, and will expire the item after diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index 3bd6993771..4b23d48fb4 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -64,7 +64,7 @@ class FileUploadHandler(object): """ Base class for streaming upload handlers. """ - chunk_size = 64 * 2 ** 10 #: The default chunk size is 64 KB. + chunk_size = 64 * 2 ** 10 # : The default chunk size is 64 KB. def __init__(self, request=None): self.file_name = None diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py index 577cb2176b..bf65687d5c 100644 --- a/django/core/handlers/base.py +++ b/django/core/handlers/base.py @@ -189,7 +189,7 @@ class BaseHandler(object): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise - except: # Handle everything else. + except: # Handle everything else. # Get the exception info now, in case another exception is thrown later. signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) @@ -199,7 +199,7 @@ class BaseHandler(object): for middleware_method in self._response_middleware: response = middleware_method(request, response) response = self.apply_response_fixes(request, response) - except: # Any exception should be gathered and handled + except: # Any exception should be gathered and handled signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, resolver, sys.exc_info()) diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py index 4c54b3e39d..21cadf48b8 100644 --- a/django/core/handlers/wsgi.py +++ b/django/core/handlers/wsgi.py @@ -52,7 +52,7 @@ class LimitedStream(object): elif size < len(self.buffer): result = self.buffer[:size] self.buffer = self.buffer[size:] - else: # size >= len(self.buffer) + else: # size >= len(self.buffer) result = self.buffer + self._read_limited(size - len(self.buffer)) self.buffer = b'' return result diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py index 3516ac330b..de49f5e241 100644 --- a/django/core/management/__init__.py +++ b/django/core/management/__init__.py @@ -121,7 +121,7 @@ def get_commands(): _commands.update(dict((name, app_name) for name in find_commands(path))) except ImportError: - pass # No management module - ignore this app + pass # No management module - ignore this app return _commands @@ -379,12 +379,12 @@ class ManagementUtility(object): options, args = parser.parse_args(self.argv) handle_default_options(options) except: # Needed because parser.parse_args can raise SystemExit - pass # Ignore any option errors at this point. + pass # Ignore any option errors at this point. try: subcommand = self.argv[1] except IndexError: - subcommand = 'help' # Display help if no arguments were given. + subcommand = 'help' # Display help if no arguments were given. if subcommand == 'help': if len(args) <= 2: diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 89549dc3c1..a24ae2b51e 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -66,9 +66,9 @@ class Command(NoArgsCommand): indexes = connection.introspection.get_indexes(cursor, table_name) except NotImplementedError: indexes = {} - used_column_names = [] # Holds column names used in the table so far + used_column_names = [] # Holds column names used in the table so far for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)): - comment_notes = [] # Holds Field notes, to be displayed in a Python comment. + comment_notes = [] # Holds Field notes, to be displayed in a Python comment. extra_params = OrderedDict() # Holds Field parameters such as 'db_column'. column_name = row[0] is_relation = i in relations @@ -112,7 +112,7 @@ class Command(NoArgsCommand): # Add 'null' and 'blank', if the 'null_ok' flag was present in the # table description. - if row[6]: # If it's NULL... + if row[6]: # If it's NULL... if field_type == 'BooleanField(': field_type = 'NullBooleanField(' else: diff --git a/django/core/urlresolvers.py b/django/core/urlresolvers.py index 723fe626be..76b50916e0 100644 --- a/django/core/urlresolvers.py +++ b/django/core/urlresolvers.py @@ -24,9 +24,9 @@ from django.utils import six from django.utils.translation import get_language -_resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances. -_ns_resolver_cache = {} # Maps namespaces to RegexURLResolver instances. -_callable_cache = {} # Maps view and url pattern names to their view functions. +_resolver_cache = {} # Maps URLconf modules to RegexURLResolver instances. +_ns_resolver_cache = {} # Maps namespaces to RegexURLResolver instances. +_callable_cache = {} # Maps view and url pattern names to their view functions. # SCRIPT_NAME prefixes for each thread are stored here. If there's no entry for # the current thread (which is the only one we ever access), it is assumed to diff --git a/django/core/validators.py b/django/core/validators.py index cf5ec7aa77..695dda258b 100644 --- a/django/core/validators.py +++ b/django/core/validators.py @@ -86,7 +86,7 @@ class EmailValidator(object): code = 'invalid' user_regex = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*$" # dot-atom - r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)', # quoted-string + r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"$)', # quoted-string re.IGNORECASE) domain_regex = re.compile( r'(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}|[A-Z0-9-]{2,})$' # domain diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index 84bbf1569f..b38d00c84a 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -226,7 +226,7 @@ class DatabaseOperations(BaseDatabaseOperations): def date_trunc_sql(self, lookup_type, field_name): fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] - format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. + format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 @@ -259,7 +259,7 @@ class DatabaseOperations(BaseDatabaseOperations): else: params = [] fields = ['year', 'month', 'day', 'hour', 'minute', 'second'] - format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. + format = ('%%Y-', '%%m', '-%%d', ' %%H:', '%%i', ':%%s') # Use double percents to escape. format_def = ('0000-', '01', '-01', ' 00:', '00', ':00') try: i = fields.index(lookup_type) + 1 @@ -300,7 +300,7 @@ class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith("`") and name.endswith("`"): - return name # Quoting once is enough. + return name # Quoting once is enough. return "`%s`" % name def quote_parameter(self, value): diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py index fc9a0d034f..6cb2f1467e 100644 --- a/django/db/backends/oracle/creation.py +++ b/django/db/backends/oracle/creation.py @@ -147,7 +147,7 @@ class DatabaseCreation(BaseDatabaseCreation): } cursor = self.connection.cursor() - time.sleep(1) # To avoid "database is being accessed by other users" errors. + time.sleep(1) # To avoid "database is being accessed by other users" errors. if self._test_user_create(): if verbosity >= 1: print('Destroying test user...') diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py index 9e6e29d5e3..43f61faf0a 100644 --- a/django/db/backends/oracle/introspection.py +++ b/django/db/backends/oracle/introspection.py @@ -52,8 +52,8 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): cursor.execute("SELECT * FROM %s WHERE ROWNUM < 2" % self.connection.ops.quote_name(table_name)) description = [] for desc in cursor.description: - name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3 - name = name % {} # cx_Oracle, for some reason, doubles percent signs. + name = force_text(desc[0]) # cx_Oracle always returns a 'str' on both Python 2 and 3 + name = name % {} # cx_Oracle, for some reason, doubles percent signs. description.append(FieldInfo(*(name.lower(),) + desc[1:])) return description diff --git a/django/db/backends/postgresql_psycopg2/introspection.py b/django/db/backends/postgresql_psycopg2/introspection.py index 046af9af55..aef0bf08aa 100644 --- a/django/db/backends/postgresql_psycopg2/introspection.py +++ b/django/db/backends/postgresql_psycopg2/introspection.py @@ -16,7 +16,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): 700: 'FloatField', 701: 'FloatField', 869: 'GenericIPAddressField', - 1042: 'CharField', # blank-padded + 1042: 'CharField', # blank-padded 1043: 'CharField', 1082: 'DateField', 1083: 'TimeField', diff --git a/django/db/backends/postgresql_psycopg2/operations.py b/django/db/backends/postgresql_psycopg2/operations.py index 723453c9c5..b9496868b0 100644 --- a/django/db/backends/postgresql_psycopg2/operations.py +++ b/django/db/backends/postgresql_psycopg2/operations.py @@ -95,7 +95,7 @@ class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith('"') and name.endswith('"'): - return name # Quoting once is enough. + return name # Quoting once is enough. return '"%s"' % name def quote_parameter(self, value): @@ -175,7 +175,7 @@ class DatabaseOperations(BaseDatabaseOperations): style.SQL_KEYWORD('IS NOT'), style.SQL_KEYWORD('FROM'), style.SQL_TABLE(qn(model._meta.db_table)))) - break # Only one AutoField is allowed per model, so don't bother continuing. + break # Only one AutoField is allowed per model, so don't bother continuing. for f in model._meta.many_to_many: if not f.rel.through: output.append("%s setval(pg_get_serial_sequence('%s','%s'), coalesce(max(%s), 1), max(%s) %s null) %s %s;" % diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 5d07f68f73..6c9728889f 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -212,7 +212,7 @@ class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith('"') and name.endswith('"'): - return name # Quoting once is enough. + return name # Quoting once is enough. return '"%s"' % name def quote_parameter(self, value): diff --git a/django/db/backends/sqlite3/introspection.py b/django/db/backends/sqlite3/introspection.py index 6ebc572e0c..da8629ace6 100644 --- a/django/db/backends/sqlite3/introspection.py +++ b/django/db/backends/sqlite3/introspection.py @@ -157,7 +157,7 @@ class DatabaseIntrospection(BaseDatabaseIntrospection): # Skip indexes across multiple fields if len(info) != 1: continue - name = info[0][2] # seqno, cid, name + name = info[0][2] # seqno, cid, name indexes[name] = {'primary_key': indexes.get(name, {}).get("primary_key", False), 'unique': unique} return indexes diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py index 095cb4efe4..8bed6415c3 100644 --- a/django/db/backends/utils.py +++ b/django/db/backends/utils.py @@ -112,21 +112,21 @@ class CursorDebugWrapper(CursorWrapper): ############################################### def typecast_date(s): - return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null + return datetime.date(*map(int, s.split('-'))) if s else None # returns None if s is null -def typecast_time(s): # does NOT store time zone information +def typecast_time(s): # does NOT store time zone information if not s: return None hour, minutes, seconds = s.split(':') - if '.' in seconds: # check whether seconds have a fractional part + if '.' in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split('.') else: microseconds = '0' return datetime.time(int(hour), int(minutes), int(seconds), int(float('.' + microseconds) * 1000000)) -def typecast_timestamp(s): # does NOT store time zone information +def typecast_timestamp(s): # does NOT store time zone information # "2005-07-29 15:48:00.590358-05" # "2005-07-29 09:56:00-05" if not s: @@ -147,7 +147,7 @@ def typecast_timestamp(s): # does NOT store time zone information dates = d.split('-') times = t.split(':') seconds = times[2] - if '.' in seconds: # check whether seconds have a fractional part + if '.' in seconds: # check whether seconds have a fractional part seconds, microseconds = seconds.split('.') else: microseconds = '0' diff --git a/django/db/models/__init__.py b/django/db/models/__init__.py index cf219d39aa..13785ed17a 100644 --- a/django/db/models/__init__.py +++ b/django/db/models/__init__.py @@ -11,7 +11,7 @@ from django.db.models.base import Model # NOQA from django.db.models.aggregates import * # NOQA from django.db.models.fields import * # NOQA from django.db.models.fields.subclassing import SubfieldBase # NOQA -from django.db.models.fields.files import FileField, ImageField # NOQA +from django.db.models.fields.files import FileField, ImageField # NOQA from django.db.models.fields.related import ( # NOQA ForeignKey, ForeignObject, OneToOneField, ManyToManyField, ManyToOneRel, ManyToManyRel, OneToOneRel) diff --git a/django/db/models/base.py b/django/db/models/base.py index 73df8633ca..ce3f095055 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -280,7 +280,7 @@ class ModelBase(type): def copy_managers(cls, base_managers): # This is in-place sorting of an Options attribute, but that's fine. base_managers.sort() - for _, mgr_name, manager in base_managers: # NOQA (redefinition of _) + for _, mgr_name, manager in base_managers: # NOQA (redefinition of _) val = getattr(cls, mgr_name, None) if not val or val is manager: new_manager = manager._copy_to_model(cls) diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 022de52134..dec2e2dd9e 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -93,7 +93,7 @@ class Field(object): # creates, creation_counter is used for all user-specified fields. creation_counter = 0 auto_creation_counter = -1 - default_validators = [] # Default set of validators + default_validators = [] # Default set of validators default_error_messages = { 'invalid_choice': _('Value %(value)r is not a valid choice.'), 'null': _('This field cannot be null.'), diff --git a/django/db/models/query.py b/django/db/models/query.py index ca49f67712..5bfa68b071 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1627,16 +1627,16 @@ def prefetch_related_objects(result_cache, related_lookups): from a QuerySet """ if len(result_cache) == 0: - return # nothing to do + return # nothing to do # We need to be able to dynamically add to the list of prefetch_related # lookups that we look up (see below). So we need some book keeping to # ensure we don't do duplicate work. - done_lookups = set() # list of lookups like foo__bar__baz + done_lookups = set() # list of lookups like foo__bar__baz done_queries = {} # dictionary of things like 'foo__bar': [results] - auto_lookups = [] # we add to this as we go through. - followed_descriptors = set() # recursion protection + auto_lookups = [] # we add to this as we go through. + followed_descriptors = set() # recursion protection all_lookups = itertools.chain(related_lookups, auto_lookups) for lookup in all_lookups: diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index 46a308f5ce..988b8bc644 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -146,7 +146,7 @@ class Query(object): # The _aggregates will be an OrderedDict when used. Due to the cost # of creating OrderedDict this attribute is created lazily (in # self.aggregates property). - self._aggregates = None # Maps alias -> SQL aggregate function + self._aggregates = None # Maps alias -> SQL aggregate function self.aggregate_select_mask = None self._aggregate_select_cache = None diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index 664a817f37..28c0195a48 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -127,7 +127,7 @@ class MultiPartParser(object): self._content_length, self._boundary, encoding) - #Check to see if it was handled + # Check to see if it was handled if result is not None: return result[0], result[1] @@ -483,7 +483,7 @@ class BoundaryIter(six.Iterator): else: # make sure we dont treat a partial boundary (and # its separators) as data - if not chunk[:-rollback]:# and len(chunk) >= (len(self._boundary) + 6): + if not chunk[:-rollback]: # and len(chunk) >= (len(self._boundary) + 6): # There's nothing left, we should just return and mark as done. self._done = True return chunk diff --git a/django/http/request.py b/django/http/request.py index 07ab6cb27d..4d11fb21e0 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -249,13 +249,13 @@ class HttpRequest(object): else: self._post, self._files = QueryDict('', encoding=self._encoding), MultiValueDict() - ## File-like and iterator interface. - ## - ## Expects self._stream to be set to an appropriate source of bytes by - ## a corresponding request subclass (e.g. WSGIRequest). - ## Also when request data has already been read by request.POST or - ## request.body, self._stream points to a BytesIO instance - ## containing that data. + # File-like and iterator interface. + # + # Expects self._stream to be set to an appropriate source of bytes by + # a corresponding request subclass (e.g. WSGIRequest). + # Also when request data has already been read by request.POST or + # request.body, self._stream points to a BytesIO instance + # containing that data. def read(self, *args, **kwargs): self._read_started = True diff --git a/django/middleware/cache.py b/django/middleware/cache.py index 96c6b24034..361e46f5e5 100644 --- a/django/middleware/cache.py +++ b/django/middleware/cache.py @@ -134,13 +134,13 @@ class FetchFromCacheMiddleware(object): """ if not request.method in ('GET', 'HEAD'): request._cache_update_cache = False - return None # Don't bother checking the cache. + return None # Don't bother checking the cache. # try and get the cached GET response cache_key = get_cache_key(request, self.key_prefix, 'GET', cache=self.cache) if cache_key is None: request._cache_update_cache = True - return None # No cache information available, need to rebuild. + return None # No cache information available, need to rebuild. response = self.cache.get(cache_key, None) # if it wasn't found and we are looking for a HEAD, try looking just for that if response is None and request.method == 'HEAD': @@ -149,7 +149,7 @@ class FetchFromCacheMiddleware(object): if response is None: request._cache_update_cache = True - return None # No cache information available, need to rebuild. + return None # No cache information available, need to rebuild. # hit, return cached response request._cache_update_cache = False diff --git a/django/templatetags/cache.py b/django/templatetags/cache.py index 0de00210fe..1ef97d7cf0 100644 --- a/django/templatetags/cache.py +++ b/django/templatetags/cache.py @@ -87,7 +87,7 @@ def do_cache(parser, token): cache_name = None return CacheNode(nodelist, parser.compile_filter(tokens[1]), - tokens[2], # fragment_name can't be a variable. + tokens[2], # fragment_name can't be a variable. [parser.compile_filter(t) for t in tokens[3:]], cache_name, ) diff --git a/django/test/_doctest.py b/django/test/_doctest.py index 2b90f1dc2e..048d886720 100644 --- a/django/test/_doctest.py +++ b/django/test/_doctest.py @@ -898,7 +898,7 @@ class DocTestFinder: elif hasattr(object, '__module__'): return module.__name__ == object.__module__ elif isinstance(object, property): - return True # [XX] no way not be sure. + return True # [XX] no way not be sure. else: raise ValueError("object must be a class or function") @@ -1221,7 +1221,7 @@ class DocTestRunner: # to modify them). original_optionflags = self.optionflags - SUCCESS, FAILURE, BOOM = range(3) # `outcome` state + SUCCESS, FAILURE, BOOM = range(3) # `outcome` state check = self._checker.check_output @@ -1274,7 +1274,7 @@ class DocTestRunner: # Strip b"" and u"" prefixes from the repr and expected output # TODO: better way of stripping the prefixes? expected = example.want - expected = expected.strip() # be wary of newlines + expected = expected.strip() # be wary of newlines s = s.replace("u", "") s = s.replace("b", "") expected = expected.replace("u", "") @@ -1288,7 +1288,7 @@ class DocTestRunner: lines.append(s) # let them match - if s == expected: # be wary of false positives here + if s == expected: # be wary of false positives here # they should be the same, print expected value sys.stdout.write("%s\n" % example.want.strip()) @@ -1314,13 +1314,13 @@ class DocTestRunner: # Don't blink! This is where the user's code gets run. six.exec_(compile(example.source, filename, "single", compileflags, 1), test.globs) - self.debugger.set_continue() # ==== Example Finished ==== + self.debugger.set_continue() # ==== Example Finished ==== exception = None except KeyboardInterrupt: raise except: exception = sys.exc_info() - self.debugger.set_continue() # ==== Example Finished ==== + self.debugger.set_continue() # ==== Example Finished ==== finally: # restore the original displayhook sys.displayhook = original_displayhook @@ -1647,11 +1647,11 @@ class OutputChecker: # Use difflib to find their differences. if optionflags & REPORT_UDIFF: diff = difflib.unified_diff(want_lines, got_lines, n=2) - diff = list(diff)[2:] # strip the diff header + diff = list(diff)[2:] # strip the diff header kind = 'unified diff with -expected +actual' elif optionflags & REPORT_CDIFF: diff = difflib.context_diff(want_lines, got_lines, n=2) - diff = list(diff)[2:] # strip the diff header + diff = list(diff)[2:] # strip the diff header kind = 'context diff with expected followed by actual' elif optionflags & REPORT_NDIFF: engine = difflib.Differ(charjunk=difflib.IS_CHARACTER_JUNK) diff --git a/django/test/simple.py b/django/test/simple.py index b2ab1269b5..05a7329fae 100644 --- a/django/test/simple.py +++ b/django/test/simple.py @@ -191,7 +191,7 @@ def build_test(label): try: if issubclass(TestClass, (unittest.TestCase, real_unittest.TestCase)): - if len(parts) == 2: # label is app.TestClass + if len(parts) == 2: # label is app.TestClass try: return unittest.TestLoader().loadTestsFromTestCase( TestClass) @@ -199,7 +199,7 @@ def build_test(label): raise ValueError( "Test label '%s' does not refer to a test class" % label) - else: # label is app.TestClass.test_method + else: # label is app.TestClass.test_method return TestClass(parts[2]) except TypeError: # TestClass isn't a TestClass - it must be a method or normal class diff --git a/django/utils/dictconfig.py b/django/utils/dictconfig.py index d01b785001..773b703497 100644 --- a/django/utils/dictconfig.py +++ b/django/utils/dictconfig.py @@ -71,7 +71,7 @@ class ConvertingDict(dict): def __getitem__(self, key): value = dict.__getitem__(self, key) result = self.configurator.convert(value) - #If the converted value is different, save for next time + # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, @@ -83,7 +83,7 @@ class ConvertingDict(dict): def get(self, key, default=None): value = dict.get(self, key, default) result = self.configurator.convert(value) - #If the converted value is different, save for next time + # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, @@ -107,7 +107,7 @@ class ConvertingList(list): def __getitem__(self, key): value = list.__getitem__(self, key) result = self.configurator.convert(value) - #If the converted value is different, save for next time + # If the converted value is different, save for next time if value is not result: self[key] = result if type(result) in (ConvertingDict, ConvertingList, @@ -197,7 +197,7 @@ class BaseConfigurator(object): else: rest = rest[m.end():] d = self.config[m.groups()[0]] - #print d, rest + # print d, rest while rest: m = self.DOT_PATTERN.match(rest) if m: @@ -219,7 +219,7 @@ class BaseConfigurator(object): else: raise ValueError('Unable to convert ' '%r at %r' % (value, rest)) - #rest should be empty + # rest should be empty return d def convert(self, value): @@ -359,25 +359,25 @@ class DictConfigurator(BaseConfigurator): '%r: %s' % (name, e)) # Next, do loggers - they refer to handlers and filters - #we don't want to lose the existing loggers, - #since other threads may have pointers to them. - #existing is set to contain all existing loggers, - #and as we go through the new configuration we - #remove any which are configured. At the end, - #what's left in existing is the set of loggers - #which were in the previous configuration but - #which are not in the new configuration. + # we don't want to lose the existing loggers, + # since other threads may have pointers to them. + # existing is set to contain all existing loggers, + # and as we go through the new configuration we + # remove any which are configured. At the end, + # what's left in existing is the set of loggers + # which were in the previous configuration but + # which are not in the new configuration. root = logging.root existing = list(root.manager.loggerDict) - #The list needs to be sorted so that we can - #avoid disabling child loggers of explicitly - #named loggers. With a sorted list it is easier - #to find the child loggers. + # The list needs to be sorted so that we can + # avoid disabling child loggers of explicitly + # named loggers. With a sorted list it is easier + # to find the child loggers. existing.sort() - #We'll keep the list of existing loggers - #which are children of named loggers here... + # We'll keep the list of existing loggers + # which are children of named loggers here... child_loggers = [] - #now set up the new ones... + # now set up the new ones... loggers = config.get('loggers', EMPTY_DICT) for name in loggers: if name in existing: @@ -397,11 +397,11 @@ class DictConfigurator(BaseConfigurator): raise ValueError('Unable to configure logger ' '%r: %s' % (name, e)) - #Disable any old loggers. There's no point deleting - #them as other threads may continue to hold references - #and by disabling them, you stop them doing any logging. - #However, don't disable children of named loggers, as that's - #probably not what was intended by the user. + # Disable any old loggers. There's no point deleting + # them as other threads may continue to hold references + # and by disabling them, you stop them doing any logging. + # However, don't disable children of named loggers, as that's + # probably not what was intended by the user. for log in existing: logger = root.manager.loggerDict[log] if log in child_loggers: @@ -431,9 +431,9 @@ class DictConfigurator(BaseConfigurator): except TypeError as te: if "'format'" not in str(te): raise - #Name of parameter changed from fmt to format. - #Retry with old name. - #This is so that code can be used with older Python versions + # Name of parameter changed from fmt to format. + # Retry with old name. + # This is so that code can be used with older Python versions #(e.g. by Django) config['fmt'] = config.pop('format') config['()'] = factory @@ -479,7 +479,7 @@ class DictConfigurator(BaseConfigurator): factory = c else: klass = self.resolve(config.pop('class')) - #Special case for handler which refers to another handler + # Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config: try: @@ -500,9 +500,9 @@ class DictConfigurator(BaseConfigurator): except TypeError as te: if "'stream'" not in str(te): raise - #The argument name changed from strm to stream - #Retry with old name. - #This is so that code can be used with older Python versions + # The argument name changed from strm to stream + # Retry with old name. + # This is so that code can be used with older Python versions #(e.g. by Django) kwargs['strm'] = kwargs.pop('stream') result = factory(**kwargs) @@ -530,7 +530,7 @@ class DictConfigurator(BaseConfigurator): if level is not None: logger.setLevel(_checkLevel(level)) if not incremental: - #Remove any existing handlers + # Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h) handlers = config.get('handlers', None) diff --git a/django/views/debug.py b/django/views/debug.py index 96d3e65189..2829ca1443 100644 --- a/django/views/debug.py +++ b/django/views/debug.py @@ -483,7 +483,7 @@ def technical_404_response(request, exception): c = Context({ 'urlconf': urlconf, 'root_urlconf': settings.ROOT_URLCONF, - 'request_path': request.path_info[1:], # Trim leading slash + 'request_path': request.path_info[1:], # Trim leading slash 'urlpatterns': tried, 'reason': force_bytes(exception, errors='replace'), 'request': request, diff --git a/docs/conf.py b/docs/conf.py index f8625e73d9..49e70fab84 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -117,7 +117,7 @@ intersphinx_mapping = { } # Python's docs don't change every week. -intersphinx_cache_limit = 90 # days +intersphinx_cache_limit = 90 # days # -- Options for HTML output --------------------------------------------------- diff --git a/setup.cfg b/setup.cfg index 9a4776a319..994c4e5431 100644 --- a/setup.cfg +++ b/setup.cfg @@ -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,./django/utils/six.py,./django/conf/app_template/* -ignore=E124,E125,E127,E128,E226,E251,E501,E261,W601 +ignore=E124,E125,E127,E128,E226,E251,E501,W601 [metadata] license-file = LICENSE diff --git a/tests/admin_changelist/admin.py b/tests/admin_changelist/admin.py index d0797581dc..42b8c959af 100644 --- a/tests/admin_changelist/admin.py +++ b/tests/admin_changelist/admin.py @@ -98,7 +98,7 @@ site.register(Parent, NoListDisplayLinksParentAdmin) class SwallowAdmin(admin.ModelAdmin): - actions = None # prevent ['action_checkbox'] + list(list_display) + actions = None # prevent ['action_checkbox'] + list(list_display) list_display = ('origin', 'load', 'speed') site.register(Swallow, SwallowAdmin) diff --git a/tests/admin_filters/models.py b/tests/admin_filters/models.py index e0b8bde2de..bd2e4e5e98 100644 --- a/tests/admin_filters/models.py +++ b/tests/admin_filters/models.py @@ -13,7 +13,7 @@ class Book(models.Model): contributors = models.ManyToManyField(User, verbose_name="Verbose Contributors", related_name='books_contributed', blank=True, null=True) is_best_seller = models.NullBooleanField(default=0) date_registered = models.DateField(null=True) - no = models.IntegerField(verbose_name='number', blank=True, null=True) # This field is intentionally 2 characters long. See #16080. + no = models.IntegerField(verbose_name='number', blank=True, null=True) # This field is intentionally 2 characters long. See #16080. def __str__(self): return self.title diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index bdfacdc206..bbec124d4d 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -78,12 +78,12 @@ class DecadeListFilterWithQuerysetBasedLookups(DecadeListFilterWithTitleAndParam class DecadeListFilterParameterEndsWith__In(DecadeListFilter): title = 'publication decade' - parameter_name = 'decade__in' # Ends with '__in" + parameter_name = 'decade__in' # Ends with '__in" class DecadeListFilterParameterEndsWith__Isnull(DecadeListFilter): title = 'publication decade' - parameter_name = 'decade__isnull' # Ends with '__isnull" + parameter_name = 'decade__isnull' # Ends with '__isnull" class DepartmentListFilterLookupWithNonStringValue(SimpleListFilter): diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py index 98c19befa4..da5ddc03b3 100644 --- a/tests/admin_inlines/admin.py +++ b/tests/admin_inlines/admin.py @@ -43,7 +43,7 @@ class AuthorAdmin(admin.ModelAdmin): class InnerInline(admin.StackedInline): model = Inner can_delete = False - readonly_fields = ('readonly',) # For bug #13174 tests. + readonly_fields = ('readonly',) # For bug #13174 tests. class HolderAdmin(admin.ModelAdmin): diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py index 763e97bd72..0085b35586 100644 --- a/tests/admin_ordering/tests.py +++ b/tests/admin_ordering/tests.py @@ -51,7 +51,7 @@ class TestAdminOrdering(TestCase): it actually changes. """ class BandAdmin(ModelAdmin): - ordering = ('rank',) # default ordering is ('name',) + ordering = ('rank',) # default ordering is ('name',) ma = BandAdmin(Band, None) names = [b.name for b in ma.get_queryset(request)] self.assertEqual(['Radiohead', 'Van Halen', 'Aerosmith'], names) diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 36b35aeefe..2aa96fbafa 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -262,7 +262,7 @@ class Podcast(Media): release_date = models.DateField() class Meta: - ordering = ('release_date',) # overridden in PodcastAdmin + ordering = ('release_date',) # overridden in PodcastAdmin class PodcastAdmin(admin.ModelAdmin): @@ -444,7 +444,7 @@ class PostAdmin(admin.ModelAdmin): class CustomChangeList(ChangeList): def get_queryset(self, request): - return self.root_queryset.filter(pk=9999) # Does not exist + return self.root_queryset.filter(pk=9999) # Does not exist class GadgetAdmin(admin.ModelAdmin): @@ -527,7 +527,7 @@ class StoryForm(forms.ModelForm): class StoryAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'content') - list_display_links = ('title',) # 'id' not in list_display_links + list_display_links = ('title',) # 'id' not in list_display_links list_editable = ('content', ) form = StoryForm ordering = ["-pk"] @@ -535,7 +535,7 @@ class StoryAdmin(admin.ModelAdmin): class OtherStoryAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'content') - list_display_links = ('title', 'id') # 'id' in list_display_links + list_display_links = ('title', 'id') # 'id' in list_display_links list_editable = ('content', ) ordering = ["-pk"] diff --git a/tests/admin_views/customadmin.py b/tests/admin_views/customadmin.py index f964d6cffb..560b4409c2 100644 --- a/tests/admin_views/customadmin.py +++ b/tests/admin_views/customadmin.py @@ -17,7 +17,7 @@ class Admin2(admin.AdminSite): login_form = forms.CustomAdminAuthenticationForm login_template = 'custom_admin/login.html' logout_template = 'custom_admin/logout.html' - index_template = ['custom_admin/index.html'] # a list, to test fix for #18697 + index_template = ['custom_admin/index.html'] # a list, to test fix for #18697 password_change_template = 'custom_admin/password_change_form.html' password_change_done_template = 'custom_admin/password_change_done.html' @@ -42,7 +42,7 @@ class UserLimitedAdmin(UserAdmin): class CustomPwdTemplateUserAdmin(UserAdmin): - change_user_password_template = ['admin/auth/user/change_password.html'] # a list, to test fix for #18697 + change_user_password_template = ['admin/auth/user/change_password.html'] # a list, to test fix for #18697 site = Admin2(name="admin2") diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index 67f3b4216a..4dcca9a4cb 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -256,7 +256,7 @@ class Podcast(Media): release_date = models.DateField() class Meta: - ordering = ('release_date',) # overridden in PodcastAdmin + ordering = ('release_date',) # overridden in PodcastAdmin class Vodcast(Media): diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index 0aa8e98933..4b36f8bd32 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -911,7 +911,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)]) - input.send_keys([Keys.BACK_SPACE]) # Clear text box + input.send_keys([Keys.BACK_SPACE]) # Clear text box self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.bob.id), str(self.cliff.id), str(self.jenny.id), @@ -922,7 +922,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas # Save and check that everything is properly stored in the database --- self.selenium.find_element_by_xpath('//input[@value="Save"]').click() self.wait_page_loaded() - self.school = models.School.objects.get(id=self.school.id) # Reload from database + self.school = models.School.objects.get(id=self.school.id) # Reload from database self.assertEqual(list(self.school.students.all()), [self.jason, self.peter]) self.assertEqual(list(self.school.alumni.all()), diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index 8e192bd082..be42a13181 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -70,7 +70,7 @@ class AggregationTests(TestCase): Regression test for #11916: Extra params + aggregation creates incorrect SQL. """ - #oracle doesn't support subqueries in group by clause + # oracle doesn't support subqueries in group by clause shortest_book_sql = """ SELECT name FROM aggregation_regress_book b diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 0c6ae91553..a79d4d9fac 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -1486,7 +1486,7 @@ class CacheI18nTest(TestCase): request = self._get_request() response = HttpResponse() with timezone.override(CustomTzName()): - CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string + CustomTzName.name = 'Hora estándar de Argentina'.encode('UTF-8') # UTF-8 string sanitized_name = 'Hora_estndar_de_Argentina' self.assertIn(sanitized_name, learn_cache_key(request, response), "Cache keys should include the time zone name when time zones are active") @@ -1645,9 +1645,9 @@ class CacheMiddlewareTest(IgnoreDeprecationWarningsMixin, TestCase): # First, test with "defaults": as_view_decorator = CacheMiddleware(cache_alias=None, key_prefix=None) - self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300 + self.assertEqual(as_view_decorator.cache_timeout, 300) # Timeout value for 'default' cache, i.e. 300 self.assertEqual(as_view_decorator.key_prefix, '') - self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache + self.assertEqual(as_view_decorator.cache_alias, 'default') # Value of DEFAULT_CACHE_ALIAS from django.core.cache self.assertEqual(as_view_decorator.cache_anonymous_only, False) # Next, test with custom values: diff --git a/tests/comment_tests/tests/test_moderation_views.py b/tests/comment_tests/tests/test_moderation_views.py index 62007e43fb..b70b01ed16 100644 --- a/tests/comment_tests/tests/test_moderation_views.py +++ b/tests/comment_tests/tests/test_moderation_views.py @@ -304,12 +304,12 @@ class AdminActionsTests(CommentTestCase): makeModerator("normaluser") self.client.login(username="normaluser", password="normaluser") with translation.override('en'): - #Test approving + # Test approving self.performActionAndCheckMessage('approve_comments', one_comment, '1 comment was successfully approved') self.performActionAndCheckMessage('approve_comments', many_comments, '3 comments were successfully approved') - #Test flagging + # Test flagging self.performActionAndCheckMessage('flag_comments', one_comment, '1 comment was successfully flagged') self.performActionAndCheckMessage('flag_comments', many_comments, '3 comments were successfully flagged') - #Test removing + # Test removing self.performActionAndCheckMessage('remove_comments', one_comment, '1 comment was successfully removed') self.performActionAndCheckMessage('remove_comments', many_comments, '3 comments were successfully removed') diff --git a/tests/datatypes/tests.py b/tests/datatypes/tests.py index 41e8a2d5d3..3cd954d3ad 100644 --- a/tests/datatypes/tests.py +++ b/tests/datatypes/tests.py @@ -37,7 +37,7 @@ class DataTypesTestCase(TestCase): self.assertEqual(d2.consumed_at, datetime.datetime(2007, 4, 20, 16, 19, 59)) def test_time_field(self): - #Test for ticket #12059: TimeField wrongly handling datetime.datetime object. + # Test for ticket #12059: TimeField wrongly handling datetime.datetime object. d = Donut(name='Apple Fritter') d.baked_time = datetime.datetime(year=2007, month=4, day=20, hour=16, minute=19, second=59) d.save() diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py index b30ef136e9..2d4e52e4d5 100644 --- a/tests/file_uploads/uploadhandler.py +++ b/tests/file_uploads/uploadhandler.py @@ -11,7 +11,7 @@ class QuotaUploadHandler(FileUploadHandler): (5MB) is uploaded. """ - QUOTA = 5 * 2**20 # 5 MB + QUOTA = 5 * 2**20 # 5 MB def __init__(self, request=None): super(QuotaUploadHandler, self).__init__(request) diff --git a/tests/forms_tests/tests/test_forms.py b/tests/forms_tests/tests/test_forms.py index aecf8f32d5..b30742106b 100644 --- a/tests/forms_tests/tests/test_forms.py +++ b/tests/forms_tests/tests/test_forms.py @@ -938,7 +938,7 @@ class FormsTestCase(TestCase): class UserRegistration(Form): username = CharField(max_length=10) # uses TextInput by default password = CharField(max_length=10, widget=PasswordInput) - realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test + realname = CharField(max_length=10, widget=TextInput) # redundantly define widget, just to test address = CharField() # no max_length defined here p = UserRegistration(auto_id=False) diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 784724bf41..cf721b5510 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -198,10 +198,10 @@ class FormsFormsetTestCase(TestCase): # number of forms to be completed. data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': '', 'choices-0-votes': '', 'choices-1-choice': '', @@ -251,10 +251,10 @@ class FormsFormsetTestCase(TestCase): # We can just fill out one of the forms. data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': '', @@ -275,10 +275,10 @@ class FormsFormsetTestCase(TestCase): # value in the returned data is not checked) data = { - 'choices-TOTAL_FORMS': '2', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', @@ -297,10 +297,10 @@ class FormsFormsetTestCase(TestCase): # value in the returned data is not checked) data = { - 'choices-TOTAL_FORMS': '2', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms - should be ignored + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', @@ -316,14 +316,14 @@ class FormsFormsetTestCase(TestCase): # And once again, if we try to partially complete a form, validation will fail. data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-1-choice': 'The Decemberists', - 'choices-1-votes': '', # missing value + 'choices-1-votes': '', # missing value 'choices-2-choice': '', 'choices-2-votes': '', } @@ -388,10 +388,10 @@ class FormsFormsetTestCase(TestCase): # 'on'. Let's go ahead and delete Fergie. data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '2', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '2', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-DELETE': '', @@ -416,10 +416,10 @@ class FormsFormsetTestCase(TestCase): field = IntegerField(min_value=100) data = { - 'check-TOTAL_FORMS': '3', # the number of forms rendered - 'check-INITIAL_FORMS': '2', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'check-MAX_NUM_FORMS': '0', # max number of forms + 'check-TOTAL_FORMS': '3', # the number of forms rendered + 'check-INITIAL_FORMS': '2', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'check-MAX_NUM_FORMS': '0', # max number of forms 'check-0-field': '200', 'check-0-DELETE': '', 'check-1-field': '50', @@ -447,7 +447,7 @@ class FormsFormsetTestCase(TestCase): can_delete=True) p = PeopleForm( - {'form-0-name': '', 'form-0-DELETE': 'on', # no name! + {'form-0-name': '', 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, 'form-MAX_NUM_FORMS': 1}) @@ -484,10 +484,10 @@ class FormsFormsetTestCase(TestCase):
  • Order:
  • """) data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '2', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '2', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', @@ -517,10 +517,10 @@ class FormsFormsetTestCase(TestCase): # they will be sorted below everything else. data = { - 'choices-TOTAL_FORMS': '4', # the number of forms rendered - 'choices-INITIAL_FORMS': '3', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '4', # the number of forms rendered + 'choices-INITIAL_FORMS': '3', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', @@ -554,10 +554,10 @@ class FormsFormsetTestCase(TestCase): # Ordering should work with blank fieldsets. data = { - 'choices-TOTAL_FORMS': '3', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '3', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms } ChoiceFormSet = formset_factory(Choice, can_order=True) @@ -607,10 +607,10 @@ class FormsFormsetTestCase(TestCase): # Let's delete Fergie, and put The Decemberists ahead of Calexico. data = { - 'choices-TOTAL_FORMS': '4', # the number of forms rendered - 'choices-INITIAL_FORMS': '3', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '4', # the number of forms rendered + 'choices-INITIAL_FORMS': '3', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', 'choices-0-ORDER': '1', @@ -653,7 +653,7 @@ class FormsFormsetTestCase(TestCase): p = PeopleForm({ 'form-0-name': '', - 'form-0-DELETE': 'on', # no name! + 'form-0-DELETE': 'on', # no name! 'form-TOTAL_FORMS': 1, 'form-INITIAL_FORMS': 1, 'form-MIN_NUM_FORMS': 0, @@ -671,10 +671,10 @@ class FormsFormsetTestCase(TestCase): # We start out with a some duplicate data. data = { - 'drinks-TOTAL_FORMS': '2', # the number of forms rendered - 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data - 'drinks-MIN_NUM_FORMS': '0', # min number of forms - 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MIN_NUM_FORMS': '0', # min number of forms + 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } @@ -691,10 +691,10 @@ class FormsFormsetTestCase(TestCase): # Make sure we didn't break the valid case. data = { - 'drinks-TOTAL_FORMS': '2', # the number of forms rendered - 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data - 'drinks-MIN_NUM_FORMS': '0', # min number of forms - 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MIN_NUM_FORMS': '0', # min number of forms + 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Bloody Mary', } @@ -859,10 +859,10 @@ class FormsFormsetTestCase(TestCase): # Regression test for #12878 ################################################# data = { - 'drinks-TOTAL_FORMS': '2', # the number of forms rendered - 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data - 'drinks-MIN_NUM_FORMS': '0', # min number of forms - 'drinks-MAX_NUM_FORMS': '0', # max number of forms + 'drinks-TOTAL_FORMS': '2', # the number of forms rendered + 'drinks-INITIAL_FORMS': '0', # the number of forms with initial data + 'drinks-MIN_NUM_FORMS': '0', # min number of forms + 'drinks-MAX_NUM_FORMS': '0', # max number of forms 'drinks-0-name': 'Gin and Tonic', 'drinks-1-name': 'Gin and Tonic', } @@ -951,7 +951,7 @@ class FormsFormsetTestCase(TestCase): data = { 'choices-TOTAL_FORMS': '1', # number of forms rendered 'choices-INITIAL_FORMS': '0', # number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', @@ -972,7 +972,7 @@ class FormsFormsetTestCase(TestCase): { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', - 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', @@ -1004,7 +1004,7 @@ class FormsFormsetTestCase(TestCase): { 'choices-TOTAL_FORMS': '4', 'choices-INITIAL_FORMS': '0', - 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MIN_NUM_FORMS': '0', # min number of forms 'choices-MAX_NUM_FORMS': '4', 'choices-0-choice': 'Zero', 'choices-0-votes': '0', @@ -1070,9 +1070,9 @@ class FormsFormsetTestCase(TestCase): def test_formset_total_error_count_with_non_form_errors(self): data = { - 'choices-TOTAL_FORMS': '2', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored + 'choices-TOTAL_FORMS': '2', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MAX_NUM_FORMS': '2', # max number of forms - should be ignored 'choices-0-choice': 'Zero', 'choices-0-votes': '0', 'choices-1-choice': 'One', @@ -1089,10 +1089,10 @@ class FormsFormsetTestCase(TestCase): data = { - 'choices-TOTAL_FORMS': '1', # the number of forms rendered - 'choices-INITIAL_FORMS': '0', # the number of forms with initial data - 'choices-MIN_NUM_FORMS': '0', # min number of forms - 'choices-MAX_NUM_FORMS': '0', # max number of forms + 'choices-TOTAL_FORMS': '1', # the number of forms rendered + 'choices-INITIAL_FORMS': '0', # the number of forms with initial data + 'choices-MIN_NUM_FORMS': '0', # min number of forms + 'choices-MAX_NUM_FORMS': '0', # max number of forms 'choices-0-choice': 'Calexico', 'choices-0-votes': '100', } @@ -1156,7 +1156,7 @@ class TestIsBoundBehavior(TestCase): 'form-0-title': 'Test', 'form-0-pub_date': '1904-06-16', 'form-1-title': 'Test', - 'form-1-pub_date': '', # <-- this date is missing but required + 'form-1-pub_date': '', # <-- this date is missing but required } formset = ArticleFormSet(data) self.assertFalse(formset.is_valid()) diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py index 95308d4eeb..25b491a499 100644 --- a/tests/forms_tests/tests/test_input_formats.py +++ b/tests/forms_tests/tests/test_input_formats.py @@ -191,7 +191,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase): result = f.clean('13.30.05') self.assertEqual(result, time(13, 30, 5)) - # # Check that the parsed result does a round trip to the same format + # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM") @@ -385,7 +385,7 @@ class LocalizedDateTests(SimpleTestCase): result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) - # # Check that the parsed result does a round trip to the same format + # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") @@ -478,7 +478,7 @@ class CustomDateInputFormatsTests(SimpleTestCase): result = f.clean('12.21.2010') self.assertEqual(result, date(2010, 12, 21)) - # # Check that the parsed result does a round trip to the same format + # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") @@ -671,7 +671,7 @@ class LocalizedDateTimeTests(SimpleTestCase): result = f.clean('13.30.05 12.21.2010') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) - # # Check that the parsed result does a round trip to the same format + # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010 13:30:05") @@ -764,7 +764,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): result = f.clean('12.21.2010 13:30:05') self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5)) - # # Check that the parsed result does a round trip to the same format + # Check that the parsed result does a round trip to the same format text = f.widget._format_value(result) self.assertEqual(text, "01:30:05 PM 21/12/2010") diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py index 1cf2f492a4..23f17f7b22 100644 --- a/tests/generic_inline_admin/tests.py +++ b/tests/generic_inline_admin/tests.py @@ -72,7 +72,7 @@ class GenericAdminViewTest(TestCase): "generic_inline_admin-media-content_type-object_id-MAX_NUM_FORMS": "0", } response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/episode/add/', post_data) - self.assertEqual(response.status_code, 302) # redirect somewhere + self.assertEqual(response.status_code, 302) # redirect somewhere def testBasicEditPost(self): """ @@ -93,7 +93,7 @@ class GenericAdminViewTest(TestCase): } url = '/generic_inline_admin/admin/generic_inline_admin/episode/%d/' % self.episode_pk response = self.client.post(url, post_data) - self.assertEqual(response.status_code, 302) # redirect somewhere + self.assertEqual(response.status_code, 302) # redirect somewhere def testGenericInlineFormset(self): EpisodeMediaFormSet = generic_inlineformset_factory(Media, can_delete=False, exclude=['description', 'keywords'], extra=3) @@ -208,7 +208,7 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase): response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/contact/add/') self.assertEqual(response.status_code, 200) response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data) - self.assertEqual(response.status_code, 302) # redirect somewhere + self.assertEqual(response.status_code, 302) # redirect somewhere class NoInlineDeletionTest(TestCase): urls = "generic_inline_admin.urls" diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index 1e099d2bb4..820aecf1f7 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -315,11 +315,11 @@ class HttpResponseTests(unittest.TestCase): self.assertEqual(r.get('test'), None) def test_non_string_content(self): - #Bug 16494: HttpResponse should behave consistently with non-strings + # Bug 16494: HttpResponse should behave consistently with non-strings r = HttpResponse(12345) self.assertEqual(r.content, b'12345') - #test content via property + # test content via property r = HttpResponse() r.content = 12345 self.assertEqual(r.content, b'12345') @@ -328,7 +328,7 @@ class HttpResponseTests(unittest.TestCase): r = HttpResponse(['abc', 'def', 'ghi']) self.assertEqual(r.content, b'abcdefghi') - #test iter content via property + # test iter content via property r = HttpResponse() r.content = ['idan', 'alex', 'jacob'] self.assertEqual(r.content, b'idanalexjacob') @@ -337,13 +337,13 @@ class HttpResponseTests(unittest.TestCase): r.content = [1, 2, 3] self.assertEqual(r.content, b'123') - #test odd inputs + # test odd inputs r = HttpResponse() r.content = ['1', '2', 3, '\u079e'] #'\xde\x9e' == unichr(1950).encode('utf-8') self.assertEqual(r.content, b'123\xde\x9e') - #with Content-Encoding header + # with Content-Encoding header r = HttpResponse() r['Content-Encoding'] = 'winning' r.content = [b'abc', b'def'] @@ -573,8 +573,8 @@ class CookieTests(unittest.TestCase): """ c = SimpleCookie() c['test'] = "An,awkward;value" - self.assertTrue(";" not in c.output().rstrip(';')) # IE compat - self.assertTrue("," not in c.output().rstrip(';')) # Safari compat + self.assertTrue(";" not in c.output().rstrip(';')) # IE compat + self.assertTrue("," not in c.output().rstrip(';')) # Safari compat def test_decode(self): """ diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index 04bc0a8632..18088e5e16 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -423,7 +423,7 @@ class LocationCommentsTests(ExtractorTests): # #21208 -- Leaky paths in comments on Windows e.g. #: path\to\file.html.py:123 bad_suffix = '.py' - bad_string = 'templates%stest.html%s' % (os.sep, bad_suffix) # + bad_string = 'templates%stest.html%s' % (os.sep, bad_suffix) self.assertFalse(bad_string in po_contents, '"%s" shouldn\'t be in final .po file.' % bad_string) diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index e8b3ac7b7d..b1f3de0ef9 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -735,7 +735,7 @@ class FormattingTests(TransRealMixin, TestCase): with self.settings(FORMAT_MODULE_PATH='i18n.other.locale'): with translation.override('de', deactivate=True): old = str("%r") % get_format_modules(reverse=True) - new = str("%r") % get_format_modules(reverse=True) # second try + new = str("%r") % get_format_modules(reverse=True) # second try self.assertEqual(new, old, 'Value returned by get_formats_modules() must be preserved between calls.') def test_localize_templatetag_and_filter(self): diff --git a/tests/invalid_models/invalid_models/models.py b/tests/invalid_models/invalid_models/models.py index 8e04a4d328..0c991dcf13 100644 --- a/tests/invalid_models/invalid_models/models.py +++ b/tests/invalid_models/invalid_models/models.py @@ -1,4 +1,4 @@ -#encoding=utf-8 +# encoding=utf-8 """ 26. Invalid models diff --git a/tests/m2m_and_m2o/tests.py b/tests/m2m_and_m2o/tests.py index ee5d77919f..35443e32e4 100644 --- a/tests/m2m_and_m2o/tests.py +++ b/tests/m2m_and_m2o/tests.py @@ -82,6 +82,6 @@ class RelatedObjectUnicodeTests(TestCase): """ m1 = UnicodeReferenceModel.objects.create() m2 = UnicodeReferenceModel.objects.create() - m2.others.add(m1) # used to cause an error (see ticket #6045) + m2.others.add(m1) # used to cause an error (see ticket #6045) m2.save() - list(m2.others.all()) # Force retrieval. + list(m2.others.all()) # Force retrieval. diff --git a/tests/max_lengths/tests.py b/tests/max_lengths/tests.py index feb3351cf7..5dd33fc80f 100644 --- a/tests/max_lengths/tests.py +++ b/tests/max_lengths/tests.py @@ -34,6 +34,6 @@ class MaxLengthORMTests(unittest.TestCase): for field in ("email", "vcard", "homepage", "avatar"): new_args = args.copy() - new_args[field] = "X" * 250 # a value longer than any of the default fields could hold. + new_args[field] = "X" * 250 # a value longer than any of the default fields could hold. p = PersonWithCustomMaxLengths.objects.create(**new_args) self.assertEqual(getattr(p, field), ("X" * 250)) diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index 2da852d11e..ddc7a4ceef 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -318,7 +318,7 @@ class ModelFormBaseTest(TestCase): class Meta: model = Category - fields = [] # url will still appear, since it is explicit above + fields = [] # url will still appear, since it is explicit above self.assertIsInstance(ReplaceField.base_fields['url'], forms.fields.BooleanField) @@ -348,7 +348,7 @@ class ModelFormBaseTest(TestCase): class CategoryForm(forms.ModelForm): class Meta: model = Category - fields = ('url') # note the missing comma + fields = ('url') # note the missing comma def test_exclude_fields(self): class ExcludeFields(forms.ModelForm): @@ -374,7 +374,7 @@ class ModelFormBaseTest(TestCase): class CategoryForm(forms.ModelForm): class Meta: model = Category - exclude = ('url') # note the missing comma + exclude = ('url') # note the missing comma def test_confused_form(self): class ConfusedForm(forms.ModelForm): @@ -415,7 +415,7 @@ class ModelFormBaseTest(TestCase): ) def test_bad_form(self): - #First class with a Meta class wins... + # First class with a Meta class wins... class BadForm(ArticleForm, BaseCategoryForm): pass @@ -818,10 +818,10 @@ class ModelToDictTests(TestCase): with self.assertNumQueries(1): d = model_to_dict(art) - #Ensure all many-to-many categories appear in model_to_dict + # Ensure all many-to-many categories appear in model_to_dict for c in categories: self.assertIn(c.pk, d['categories']) - #Ensure many-to-many relation appears as a list + # Ensure many-to-many relation appears as a list self.assertIsInstance(d['categories'], list) class OldFormForXTests(TestCase): diff --git a/tests/model_formsets/tests.py b/tests/model_formsets/tests.py index 4c57e0f549..ac9d68132e 100644 --- a/tests/model_formsets/tests.py +++ b/tests/model_formsets/tests.py @@ -54,8 +54,8 @@ class DeletionTests(TestCase): 'form-0-id': six.text_type(poet.id), 'form-0-name': 'test', 'form-1-id': '', - 'form-1-name': 'x' * 1000, # Too long - 'form-1-id': six.text_type(poet.id), # Violate unique constraint + 'form-1-name': 'x' * 1000, # Too long + 'form-1-id': six.text_type(poet.id), # Violate unique constraint 'form-1-name': 'test2', } formset = PoetFormSet(data, queryset=Poet.objects.all()) @@ -145,9 +145,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'form-TOTAL_FORMS': '3', # the number of forms rendered - 'form-INITIAL_FORMS': '0', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '3', # the number of forms rendered + 'form-INITIAL_FORMS': '0', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Charles Baudelaire', 'form-1-name': 'Arthur Rimbaud', 'form-2-name': '', @@ -183,9 +183,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'form-TOTAL_FORMS': '3', # the number of forms rendered - 'form-INITIAL_FORMS': '2', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '3', # the number of forms rendered + 'form-INITIAL_FORMS': '2', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), @@ -227,9 +227,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'form-TOTAL_FORMS': '4', # the number of forms rendered - 'form-INITIAL_FORMS': '3', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '4', # the number of forms rendered + 'form-INITIAL_FORMS': '3', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Arthur Rimbaud', 'form-1-id': str(author1.id), @@ -253,9 +253,9 @@ class ModelFormsetTest(TestCase): # Let's edit a record to ensure save only returns that one record. data = { - 'form-TOTAL_FORMS': '4', # the number of forms rendered - 'form-INITIAL_FORMS': '3', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '4', # the number of forms rendered + 'form-INITIAL_FORMS': '3', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(author2.id), 'form-0-name': 'Walt Whitman', 'form-1-id': str(author1.id), @@ -291,9 +291,9 @@ class ModelFormsetTest(TestCase): AuthorMeetingFormSet = modelformset_factory(AuthorMeeting, fields="__all__", extra=1, can_delete=True) data = { - 'form-TOTAL_FORMS': '2', # the number of forms rendered - 'form-INITIAL_FORMS': '1', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '2', # the number of forms rendered + 'form-INITIAL_FORMS': '1', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-id': str(meeting.id), 'form-0-name': '2nd Tuesday of the Week Meeting', 'form-0-authors': [author2.id, author1.id, author3.id, author4.id], @@ -379,9 +379,9 @@ class ModelFormsetTest(TestCase): PoetFormSet = modelformset_factory(Poet, fields="__all__", form=PoetForm) data = { - 'form-TOTAL_FORMS': '3', # the number of forms rendered - 'form-INITIAL_FORMS': '0', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '3', # the number of forms rendered + 'form-INITIAL_FORMS': '0', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-name': 'Walt Whitman', 'form-1-name': 'Charles Baudelaire', 'form-2-name': '', @@ -445,9 +445,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'form-TOTAL_FORMS': '1', # the number of forms rendered - 'form-INITIAL_FORMS': '0', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '1', # the number of forms rendered + 'form-INITIAL_FORMS': '0', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': '', 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', @@ -471,9 +471,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'form-TOTAL_FORMS': '2', # the number of forms rendered - 'form-INITIAL_FORMS': '1', # the number of forms with initial data - 'form-MAX_NUM_FORMS': '', # the max number of forms + 'form-TOTAL_FORMS': '2', # the number of forms rendered + 'form-INITIAL_FORMS': '1', # the number of forms with initial data + 'form-MAX_NUM_FORMS': '', # the max number of forms 'form-0-author_ptr': hemingway_id, 'form-0-name': 'Ernest Hemingway', 'form-0-write_speed': '10', @@ -503,9 +503,9 @@ class ModelFormsetTest(TestCase): '

    ' % author.id) data = { - 'book_set-TOTAL_FORMS': '3', # the number of forms rendered - 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data - 'book_set-MAX_NUM_FORMS': '', # the max number of forms + 'book_set-TOTAL_FORMS': '3', # the number of forms rendered + 'book_set-INITIAL_FORMS': '0', # the number of forms with initial data + 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': '', 'book_set-2-title': '', @@ -537,9 +537,9 @@ class ModelFormsetTest(TestCase): '

    ' % author.id) data = { - 'book_set-TOTAL_FORMS': '3', # the number of forms rendered - 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data - 'book_set-MAX_NUM_FORMS': '', # the max number of forms + 'book_set-TOTAL_FORMS': '3', # the number of forms rendered + 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data + 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-title': 'Les Paradis Artificiels', @@ -568,9 +568,9 @@ class ModelFormsetTest(TestCase): Author.objects.create(name='Charles Baudelaire') data = { - 'book_set-TOTAL_FORMS': '3', # the number of forms rendered - 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data - 'book_set-MAX_NUM_FORMS': '', # the max number of forms + 'book_set-TOTAL_FORMS': '3', # the number of forms rendered + 'book_set-INITIAL_FORMS': '2', # the number of forms with initial data + 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': '1', 'book_set-0-title': 'Les Fleurs du Mal', 'book_set-1-id': '2', @@ -613,9 +613,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered - 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data - 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms + 'bookwithcustompk_set-TOTAL_FORMS': '1', # the number of forms rendered + 'bookwithcustompk_set-INITIAL_FORMS': '0', # the number of forms with initial data + 'bookwithcustompk_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithcustompk_set-0-my_pk': '77777', 'bookwithcustompk_set-0-title': 'Les Fleurs du Mal', } @@ -645,9 +645,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered - 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data - 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms + 'alternatebook_set-TOTAL_FORMS': '1', # the number of forms rendered + 'alternatebook_set-INITIAL_FORMS': '0', # the number of forms with initial data + 'alternatebook_set-MAX_NUM_FORMS': '', # the max number of forms 'alternatebook_set-0-title': 'Flowers of Evil', 'alternatebook_set-0-notes': 'English translation of Les Fleurs du Mal' } @@ -670,9 +670,9 @@ class ModelFormsetTest(TestCase): author = Author.objects.create(pk=1, name='Charles Baudelaire') data = { - 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered - 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data - 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms + 'bookwithoptionalalteditor_set-TOTAL_FORMS': '2', # the number of forms rendered + 'bookwithoptionalalteditor_set-INITIAL_FORMS': '0', # the number of forms with initial data + 'bookwithoptionalalteditor_set-MAX_NUM_FORMS': '', # the max number of forms 'bookwithoptionalalteditor_set-0-author': '1', 'bookwithoptionalalteditor_set-0-title': 'Les Fleurs du Mal', 'bookwithoptionalalteditor_set-1-author': '1', @@ -708,9 +708,9 @@ class ModelFormsetTest(TestCase): PoemFormSet = inlineformset_factory(Poet, Poem, form=PoemForm, fields="__all__") data = { - 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered - 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data - 'poem_set-MAX_NUM_FORMS': '', # the max number of forms + 'poem_set-TOTAL_FORMS': '3', # the number of forms rendered + 'poem_set-INITIAL_FORMS': '0', # the number of forms with initial data + 'poem_set-MAX_NUM_FORMS': '', # the max number of forms 'poem_set-0-name': 'The Cloud in Trousers', 'poem_set-1-name': 'I', 'poem_set-2-name': '', @@ -743,9 +743,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'book_set-TOTAL_FORMS': '5', # the number of forms rendered - 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data - 'book_set-MAX_NUM_FORMS': '', # the max number of forms + 'book_set-TOTAL_FORMS': '5', # the number of forms rendered + 'book_set-INITIAL_FORMS': '3', # the number of forms with initial data + 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book1.id), 'book_set-0-title': 'Les Paradis Artificiels', 'book_set-1-id': str(book2.id), @@ -768,9 +768,9 @@ class ModelFormsetTest(TestCase): '

    ') data = { - 'book_set-TOTAL_FORMS': '3', # the number of forms rendered - 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data - 'book_set-MAX_NUM_FORMS': '', # the max number of forms + 'book_set-TOTAL_FORMS': '3', # the number of forms rendered + 'book_set-INITIAL_FORMS': '1', # the number of forms with initial data + 'book_set-MAX_NUM_FORMS': '', # the max number of forms 'book_set-0-id': str(book3.id), 'book_set-0-title': 'Flowers of Evil', 'book_set-1-title': 'Revue des deux mondes', @@ -958,7 +958,7 @@ class ModelFormsetTest(TestCase): data = { 'form-TOTAL_FORMS': '2', 'form-INITIAL_FORMS': '0', - 'form-MAX_NUM_FORMS': '2', # should be ignored + 'form-MAX_NUM_FORMS': '2', # should be ignored 'form-0-price': '12.00', 'form-0-quantity': '1', 'form-1-price': '24.00', @@ -1064,7 +1064,7 @@ class ModelFormsetTest(TestCase): # default. This is required to ensure the value is tested for change correctly # when determine what extra forms have changed to save. - self.assertEqual(len(formset.forms), 1) # this formset only has one form + self.assertEqual(len(formset.forms), 1) # this formset only has one form form = formset.forms[0] now = form.fields['date_joined'].initial() result = form.as_p() diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py index 4789e35a43..27f54821d6 100644 --- a/tests/modeladmin/models.py +++ b/tests/modeladmin/models.py @@ -35,7 +35,7 @@ class ValidationTestModel(models.Model): is_active = models.BooleanField(default=False) pub_date = models.DateTimeField() band = models.ForeignKey(Band) - no = models.IntegerField(verbose_name="Number", blank=True, null=True) # This field is intentionally 2 characters long. See #16080. + no = models.IntegerField(verbose_name="Number", blank=True, null=True) # This field is intentionally 2 characters long. See #16080. def decade_published_in(self): return self.pub_date.strftime('%Y')[:3] + "0's" diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index 046b8fb14b..8596346c7e 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -1791,10 +1791,10 @@ class RouterAttributeErrorTestCase(TestCase): def test_attribute_error_read(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" - router.routers = [] # Reset routers so we can save a Book instance + router.routers = [] # Reset routers so we can save a Book instance b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) - router.routers = [AttributeErrorRouter()] # Install our router + router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, Book.objects.get, pk=b.pk) def test_attribute_error_save(self): @@ -1806,22 +1806,22 @@ class RouterAttributeErrorTestCase(TestCase): def test_attribute_error_delete(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" - router.routers = [] # Reset routers so we can save our Book, Person instances + router.routers = [] # Reset routers so we can save our Book, Person instances b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") b.authors = [p] b.editor = p - router.routers = [AttributeErrorRouter()] # Install our router + router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, b.delete) def test_attribute_error_m2m(self): "Check that the AttributeError from AttributeErrorRouter bubbles up" - router.routers = [] # Reset routers so we can save our Book, Person instances + router.routers = [] # Reset routers so we can save our Book, Person instances b = Book.objects.create(title="Pro Django", published=datetime.date(2008, 12, 16)) p = Person.objects.create(name="Marty Alchin") - router.routers = [AttributeErrorRouter()] # Install our router + router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, setattr, b, 'authors', [p]) class ModelMetaRouter(object): diff --git a/tests/null_fk/tests.py b/tests/null_fk/tests.py index 29e1fcb4bb..d5b68658ff 100644 --- a/tests/null_fk/tests.py +++ b/tests/null_fk/tests.py @@ -50,7 +50,7 @@ class NullFkTests(TestCase): item = Item.objects.create(title='Some Item') pv = PropertyValue.objects.create(label='Some Value') item.props.create(key='a', value=pv) - item.props.create(key='b') # value=NULL + item.props.create(key='b') # value=NULL q1 = Q(props__key='a', props__value=pv) q2 = Q(props__key='b', props__value__isnull=True) diff --git a/tests/queryset_pickle/tests.py b/tests/queryset_pickle/tests.py index 7ce4348c1a..077ac6f59c 100644 --- a/tests/queryset_pickle/tests.py +++ b/tests/queryset_pickle/tests.py @@ -10,7 +10,7 @@ from .models import Group, Event, Happening, Container, M2MModel class PickleabilityTestCase(TestCase): def setUp(self): - Happening.objects.create() # make sure the defaults are working (#20158) + Happening.objects.create() # make sure the defaults are working (#20158) def assert_pickles(self, qs): self.assertEqual(list(pickle.loads(pickle.dumps(qs))), list(qs)) diff --git a/tests/requests/tests.py b/tests/requests/tests.py index 137b324588..c00f5bb5e0 100644 --- a/tests/requests/tests.py +++ b/tests/requests/tests.py @@ -524,7 +524,7 @@ class HostValidationTests(SimpleTestCase): '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', - 'xn--4ca9at.com', # Punnycode for öäü.com + 'xn--4ca9at.com', # Punnycode for öäü.com 'anything.multitenant.com', 'multitenant.com', 'insensitive.com', @@ -594,7 +594,7 @@ class HostValidationTests(SimpleTestCase): '12.34.56.78:443', '[2001:19f0:feee::dead:beef:cafe]', '[2001:19f0:feee::dead:beef:cafe]:8080', - 'xn--4ca9at.com', # Punnycode for öäü.com + 'xn--4ca9at.com', # Punnycode for öäü.com ] for host in legit_hosts: @@ -636,11 +636,11 @@ class HostValidationTests(SimpleTestCase): msg_suggestion = msg_invalid_host + "You may need to add %r to ALLOWED_HOSTS." msg_suggestion2 = msg_invalid_host + "The domain name provided is not valid according to RFC 1034/1035" - for host in [ # Valid-looking hosts + for host in [ # Valid-looking hosts 'example.com', '12.34.56.78', '[2001:19f0:feee::dead:beef:cafe]', - 'xn--4ca9at.com', # Punnycode for öäü.com + 'xn--4ca9at.com', # Punnycode for öäü.com ]: request = HttpRequest() request.META = {'HTTP_HOST': host} @@ -650,7 +650,7 @@ class HostValidationTests(SimpleTestCase): request.get_host ) - for domain, port in [ # Valid-looking hosts with a port number + for domain, port in [ # Valid-looking hosts with a port number ('example.com', 80), ('12.34.56.78', 443), ('[2001:19f0:feee::dead:beef:cafe]', 8080), diff --git a/tests/serializers_regress/tests.py b/tests/serializers_regress/tests.py index c8f29f471e..d71dd8c406 100644 --- a/tests/serializers_regress/tests.py +++ b/tests/serializers_regress/tests.py @@ -308,7 +308,7 @@ The end."""), (im2m_obj, 470, M2MIntermediateData, None), - #testing post- and prereferences and extra fields + # testing post- and prereferences and extra fields (im_obj, 480, Intermediate, {'right': 300, 'left': 470}), (im_obj, 481, Intermediate, {'right': 300, 'left': 490}), (im_obj, 482, Intermediate, {'right': 500, 'left': 470}), diff --git a/tests/template_tests/filters.py b/tests/template_tests/filters.py index 0531fb09cf..ad85d0cb0b 100644 --- a/tests/template_tests/filters.py +++ b/tests/template_tests/filters.py @@ -357,7 +357,7 @@ def get_filter_tests(): 'date01': (r'{{ d|date:"m" }}', {'d': datetime(2008, 1, 1)}, '01'), 'date02': (r'{{ d|date }}', {'d': datetime(2008, 1, 1)}, 'Jan. 1, 2008'), - #Ticket 9520: Make sure |date doesn't blow up on non-dates + # Ticket 9520: Make sure |date doesn't blow up on non-dates 'date03': (r'{{ d|date:"m" }}', {'d': 'fail_string'}, ''), # ISO date formats 'date04': (r'{{ d|date:"o" }}', {'d': datetime(2008, 12, 29)}, '2009'), diff --git a/tests/template_tests/tests.py b/tests/template_tests/tests.py index 9ee845ec51..bad15e2834 100644 --- a/tests/template_tests/tests.py +++ b/tests/template_tests/tests.py @@ -853,7 +853,7 @@ class TemplateTests(TransRealMixin, TestCase): # Numbers as filter arguments should work 'filter-syntax19': ('{{ var|truncatewords:1 }}', {"var": "hello world"}, "hello ..."), - #filters should accept empty string constants + # filters should accept empty string constants 'filter-syntax20': ('{{ ""|default_if_none:"was none" }}', {}, ""), # Fail silently for non-callable attribute and dict lookups which diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index 75801427d3..14191306c4 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -439,7 +439,7 @@ class ClientTest(TestCase): "Request a page that is known to throw an error" self.assertRaises(KeyError, self.client.get, "/test_client/broken_view/") - #Try the same assertion, a different way + # Try the same assertion, a different way try: self.client.get('/test_client/broken_view/') self.fail('Should raise an error') diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index 83d6a0097e..04fa734ddc 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -122,14 +122,14 @@ class AssertContainsTests(TestCase): def test_unicode_contains(self): "Unicode characters can be found in template context" - #Regression test for #10183 + # Regression test for #10183 r = self.client.get('/test_client_regress/check_unicode/') self.assertContains(r, 'さかき') self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8')) def test_unicode_not_contains(self): "Unicode characters can be searched for, and not found in template context" - #Regression test for #10183 + # Regression test for #10183 r = self.client.get('/test_client_regress/check_unicode/') self.assertNotContains(r, 'はたけ') self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8')) @@ -1204,7 +1204,7 @@ class UnicodePayloadTests(TestCase): def test_unicode_payload_non_utf(self): "A non-ASCII unicode data as a non-UTF based encoding can be POSTed" - #Regression test for #10571 + # Regression test for #10571 json = '{"dog": "собака"}' response = self.client.post("/test_client_regress/parse_unicode_json/", json, content_type="application/json; charset=koi8-r") diff --git a/tests/view_tests/__init__.py b/tests/view_tests/__init__.py index b031e205e0..371ab40b40 100644 --- a/tests/view_tests/__init__.py +++ b/tests/view_tests/__init__.py @@ -7,5 +7,5 @@ class BrokenException(Exception): except_args = (b'Broken!', # plain exception with ASCII text '¡Broken!', # non-ASCII unicode data - '¡Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring + '¡Broken!'.encode('utf-8'), # non-ASCII, utf-8 encoded bytestring b'\xa1Broken!', ) # non-ASCII, latin1 bytestring diff --git a/tests/view_tests/tests/test_defaults.py b/tests/view_tests/tests/test_defaults.py index 13e56d604b..128fb7cb07 100644 --- a/tests/view_tests/tests/test_defaults.py +++ b/tests/view_tests/tests/test_defaults.py @@ -10,8 +10,8 @@ from ..models import UrlArticle class DefaultsTests(TestCase): """Test django views in django/views/defaults.py""" fixtures = ['testdata.json'] - non_existing_urls = ['/views/non_existing_url/', # this is in urls.py - '/views/other_non_existing_url/'] # this NOT in urls.py + non_existing_urls = ['/views/non_existing_url/', # this is in urls.py + '/views/other_non_existing_url/'] # this NOT in urls.py def test_page_not_found(self): "A 404 status is returned by the page_not_found view" -- cgit v1.3 From 3f115776e1ffaf7b48976f88faf36c423e544d1d Mon Sep 17 00:00:00 2001 From: Jason Myers Date: Sat, 2 Nov 2013 17:50:35 -0500 Subject: PEP8 Signed-off-by: Jason Myers --- tests/admin_views/admin.py | 22 ++++++++++++++ tests/decorators/tests.py | 3 +- tests/defer/models.py | 4 +++ tests/defer_regress/models.py | 14 +++++++++ tests/model_forms/tests.py | 11 +++++-- tests/model_forms_regress/models.py | 12 ++++++++ tests/model_forms_regress/tests.py | 7 ++++- tests/model_formsets/models.py | 26 +++++++++++++++++ tests/model_formsets_regress/models.py | 6 ++++ tests/model_formsets_regress/tests.py | 1 + tests/model_inheritance/models.py | 22 ++++++++++++++ tests/model_inheritance_regress/models.py | 37 ++++++++++++++++++++++++ tests/model_inheritance_select_related/models.py | 2 ++ tests/model_validation/models.py | 1 + tests/modeladmin/models.py | 3 ++ tests/multiple_database/models.py | 6 ++++ 16 files changed, 172 insertions(+), 5 deletions(-) (limited to 'tests/multiple_database') diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 2aa96fbafa..039383a7dc 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -58,6 +58,7 @@ class ArticleInline(admin.TabularInline): }) ) + class ChapterInline(admin.TabularInline): model = Chapter @@ -578,10 +579,12 @@ class AdminOrderedFieldAdmin(admin.ModelAdmin): ordering = ('order',) list_display = ('stuff', 'order') + class AdminOrderedModelMethodAdmin(admin.ModelAdmin): ordering = ('order',) list_display = ('stuff', 'some_order') + class AdminOrderedAdminMethodAdmin(admin.ModelAdmin): def some_admin_order(self, obj): return obj.order @@ -589,13 +592,17 @@ class AdminOrderedAdminMethodAdmin(admin.ModelAdmin): ordering = ('order',) list_display = ('stuff', 'some_admin_order') + def admin_ordered_callable(obj): return obj.order admin_ordered_callable.admin_order_field = 'order' + + class AdminOrderedCallableAdmin(admin.ModelAdmin): ordering = ('order',) list_display = ('stuff', admin_ordered_callable) + class ReportAdmin(admin.ModelAdmin): def extra(self, request): return HttpResponse() @@ -612,6 +619,7 @@ class ReportAdmin(admin.ModelAdmin): class CustomTemplateBooleanFieldListFilter(BooleanFieldListFilter): template = 'custom_filter_template.html' + class CustomTemplateFilterColorAdmin(admin.ModelAdmin): list_filter = (('warm', CustomTemplateBooleanFieldListFilter),) @@ -628,12 +636,14 @@ class RelatedPrepopulatedInline1(admin.StackedInline): prepopulated_fields = {'slug1': ['name', 'pubdate'], 'slug2': ['status', 'name']} + class RelatedPrepopulatedInline2(admin.TabularInline): model = RelatedPrepopulated extra = 1 prepopulated_fields = {'slug1': ['name', 'pubdate'], 'slug2': ['status', 'name']} + class MainPrepopulatedAdmin(admin.ModelAdmin): inlines = [RelatedPrepopulatedInline1, RelatedPrepopulatedInline2] fieldsets = ( @@ -712,14 +722,17 @@ class FormWithoutHiddenField(forms.ModelForm): first = forms.CharField() second = forms.CharField() + class FormWithoutVisibleField(forms.ModelForm): first = forms.CharField(widget=forms.HiddenInput) second = forms.CharField(widget=forms.HiddenInput) + class FormWithVisibleAndHiddenField(forms.ModelForm): first = forms.CharField(widget=forms.HiddenInput) second = forms.CharField() + class EmptyModelVisibleAdmin(admin.ModelAdmin): form = FormWithoutHiddenField fieldsets = ( @@ -728,39 +741,48 @@ class EmptyModelVisibleAdmin(admin.ModelAdmin): }), ) + class EmptyModelHiddenAdmin(admin.ModelAdmin): form = FormWithoutVisibleField fieldsets = EmptyModelVisibleAdmin.fieldsets + class EmptyModelMixinAdmin(admin.ModelAdmin): form = FormWithVisibleAndHiddenField fieldsets = EmptyModelVisibleAdmin.fieldsets + class CityInlineAdmin(admin.TabularInline): model = City view_on_site = False + class StateAdmin(admin.ModelAdmin): inlines = [CityInlineAdmin] + class RestaurantInlineAdmin(admin.TabularInline): model = Restaurant view_on_site = True + class CityAdmin(admin.ModelAdmin): inlines = [RestaurantInlineAdmin] view_on_site = True + class WorkerAdmin(admin.ModelAdmin): def view_on_site(self, obj): return '/worker/%s/%s/' % (obj.surname, obj.name) + class WorkerInlineAdmin(admin.TabularInline): model = Worker def view_on_site(self, obj): return '/worker_inline/%s/%s/' % (obj.surname, obj.name) + class RestaurantAdmin(admin.ModelAdmin): inlines = [WorkerInlineAdmin] view_on_site = False diff --git a/tests/decorators/tests.py b/tests/decorators/tests.py index 4016273ef5..db00f36051 100644 --- a/tests/decorators/tests.py +++ b/tests/decorators/tests.py @@ -44,7 +44,7 @@ full_decorator = compose( vary_on_cookie, # django.views.decorators.cache - cache_page(60*15), + cache_page(60 * 15), cache_control(private=True), never_cache, @@ -65,6 +65,7 @@ full_decorator = compose( fully_decorated = full_decorator(fully_decorated) + class DecoratorsTest(TestCase): def test_attributes(self): diff --git a/tests/defer/models.py b/tests/defer/models.py index cf3bae86bb..ffc8a0c2c7 100644 --- a/tests/defer/models.py +++ b/tests/defer/models.py @@ -10,6 +10,7 @@ class Secondary(models.Model): first = models.CharField(max_length=50) second = models.CharField(max_length=50) + @python_2_unicode_compatible class Primary(models.Model): name = models.CharField(max_length=50) @@ -19,12 +20,15 @@ class Primary(models.Model): def __str__(self): return self.name + class Child(Primary): pass + class BigChild(Primary): other = models.CharField(max_length=50) + class ChildProxy(Child): class Meta: proxy = True diff --git a/tests/defer_regress/models.py b/tests/defer_regress/models.py index 0170221cb9..d858558e97 100644 --- a/tests/defer_regress/models.py +++ b/tests/defer_regress/models.py @@ -16,13 +16,16 @@ class Item(models.Model): def __str__(self): return self.name + class RelatedItem(models.Model): item = models.ForeignKey(Item) + class Child(models.Model): name = models.CharField(max_length=10) value = models.IntegerField() + @python_2_unicode_compatible class Leaf(models.Model): name = models.CharField(max_length=10) @@ -33,14 +36,17 @@ class Leaf(models.Model): def __str__(self): return self.name + class ResolveThis(models.Model): num = models.FloatField() name = models.CharField(max_length=16) + class Proxy(Item): class Meta: proxy = True + @python_2_unicode_compatible class SimpleItem(models.Model): name = models.CharField(max_length=15) @@ -49,29 +55,37 @@ class SimpleItem(models.Model): def __str__(self): return self.name + class Feature(models.Model): item = models.ForeignKey(SimpleItem) + class SpecialFeature(models.Model): feature = models.ForeignKey(Feature) + class OneToOneItem(models.Model): item = models.OneToOneField(Item, related_name="one_to_one_item") name = models.CharField(max_length=15) + class ItemAndSimpleItem(models.Model): item = models.ForeignKey(Item) simple = models.ForeignKey(SimpleItem) + class Profile(models.Model): profile1 = models.CharField(max_length=1000, default='profile1') + class Location(models.Model): location1 = models.CharField(max_length=1000, default='location1') + class Item(models.Model): pass + class Request(models.Model): profile = models.ForeignKey(Profile, null=True, blank=True) location = models.ForeignKey(Location) diff --git a/tests/model_forms/tests.py b/tests/model_forms/tests.py index ddc7a4ceef..5e443011c2 100644 --- a/tests/model_forms/tests.py +++ b/tests/model_forms/tests.py @@ -185,6 +185,7 @@ class BetterWriterForm(forms.ModelForm): model = BetterWriter fields = '__all__' + class WriterProfileForm(forms.ModelForm): class Meta: model = WriterProfile @@ -234,6 +235,7 @@ class ColourfulItemForm(forms.ModelForm): # model forms for testing work on #9321: + class StatusNoteForm(forms.ModelForm): class Meta: model = ArticleStatusNote @@ -295,7 +297,7 @@ class ModelFormBaseTest(TestCase): fields = '__all__' self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + forms.fields.BooleanField) def test_replace_field_variant_2(self): # Should have the same result as before, @@ -308,7 +310,7 @@ class ModelFormBaseTest(TestCase): fields = ['url'] self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + forms.fields.BooleanField) def test_replace_field_variant_3(self): # Should have the same result as before, @@ -321,7 +323,7 @@ class ModelFormBaseTest(TestCase): fields = [] # url will still appear, since it is explicit above self.assertIsInstance(ReplaceField.base_fields['url'], - forms.fields.BooleanField) + forms.fields.BooleanField) def test_override_field(self): class WriterForm(forms.ModelForm): @@ -583,6 +585,7 @@ class IncompleteCategoryFormWithFields(forms.ModelForm): fields = ('name', 'slug') model = Category + class IncompleteCategoryFormWithExclude(forms.ModelForm): """ A form that replaces the model's url field with a custom one. This should @@ -788,6 +791,7 @@ class UniqueTest(TestCase): "slug": "Django 1.0"}, instance=p) self.assertTrue(form.is_valid()) + class ModelToDictTests(TestCase): """ Tests for forms.models.model_to_dict @@ -824,6 +828,7 @@ class ModelToDictTests(TestCase): # Ensure many-to-many relation appears as a list self.assertIsInstance(d['categories'], list) + class OldFormForXTests(TestCase): def test_base_form(self): self.assertEqual(Category.objects.count(), 0) diff --git a/tests/model_forms_regress/models.py b/tests/model_forms_regress/models.py index 2c2fd39158..396bd1eaa4 100644 --- a/tests/model_forms_regress/models.py +++ b/tests/model_forms_regress/models.py @@ -11,6 +11,7 @@ from django.utils._os import upath class Person(models.Model): name = models.CharField(max_length=100) + class Triple(models.Model): left = models.IntegerField() middle = models.IntegerField() @@ -19,9 +20,11 @@ class Triple(models.Model): class Meta: unique_together = (('left', 'middle'), ('middle', 'right')) + class FilePathModel(models.Model): path = models.FilePathField(path=os.path.dirname(upath(__file__)), match=".*\.py$", blank=True) + @python_2_unicode_compatible class Publication(models.Model): title = models.CharField(max_length=30) @@ -30,6 +33,7 @@ class Publication(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) @@ -38,15 +42,18 @@ class Article(models.Model): def __str__(self): return self.headline + class CustomFileField(models.FileField): def save_form_data(self, instance, data): been_here = getattr(self, 'been_saved', False) assert not been_here, "save_form_data called more than once" setattr(self, 'been_saved', True) + class CustomFF(models.Model): f = CustomFileField(upload_to='unused', blank=True) + class RealPerson(models.Model): name = models.CharField(max_length=100) @@ -54,20 +61,25 @@ class RealPerson(models.Model): if self.name.lower() == 'anonymous': raise ValidationError("Please specify a real name.") + class Author(models.Model): publication = models.OneToOneField(Publication, null=True, blank=True) full_name = models.CharField(max_length=255) + class Author1(models.Model): publication = models.OneToOneField(Publication, null=False) full_name = models.CharField(max_length=255) + class Homepage(models.Model): url = models.URLField() + class Document(models.Model): myfile = models.FileField(upload_to='unused', blank=True) + class Edition(models.Model): author = models.ForeignKey(Person) publication = models.ForeignKey(Publication) diff --git a/tests/model_forms_regress/tests.py b/tests/model_forms_regress/tests.py index b7f4cf5979..963c7e552d 100644 --- a/tests/model_forms_regress/tests.py +++ b/tests/model_forms_regress/tests.py @@ -106,6 +106,7 @@ class FullyLocalizedTripleForm(forms.ModelForm): localized_fields = '__all__' fields = '__all__' + class LocalizedModelFormTest(TestCase): def test_model_form_applies_localize_to_some_fields(self): f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10}) @@ -167,6 +168,7 @@ class FilePathFieldTests(TestCase): names.sort() self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py']) + class ManyToManyCallableInitialTests(TestCase): def test_callable(self): "Regression for #10349: A callable can be provided as the initial value for an m2m field" @@ -207,9 +209,10 @@ class CustomFieldSaveTests(TestCase): # It's enough that the form saves without error -- the custom save routine will # generate an AssertionError if it is called more than once during save. - form = CFFForm(data = {'f': None}) + form = CFFForm(data={'f': None}) form.save() + class ModelChoiceIteratorTests(TestCase): def test_len(self): class Form(forms.ModelForm): @@ -236,12 +239,14 @@ class CustomModelFormSaveMethod(TestCase): self.assertEqual(form.is_valid(), False) self.assertEqual(form.errors['__all__'], ['Please specify a real name.']) + class ModelClassTests(TestCase): def test_no_model_class(self): class NoModelModelForm(forms.ModelForm): pass self.assertRaises(ValueError, NoModelModelForm) + class OneToOneFieldTests(TestCase): def test_assignment_of_none(self): class AuthorForm(forms.ModelForm): diff --git a/tests/model_formsets/models.py b/tests/model_formsets/models.py index adeb3455a4..da79c6a573 100644 --- a/tests/model_formsets/models.py +++ b/tests/model_formsets/models.py @@ -17,9 +17,11 @@ class Author(models.Model): def __str__(self): return self.name + class BetterAuthor(Author): write_speed = models.IntegerField() + @python_2_unicode_compatible class Book(models.Model): author = models.ForeignKey(Author) @@ -34,6 +36,7 @@ class Book(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class BookWithCustomPK(models.Model): my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True) @@ -43,9 +46,11 @@ class BookWithCustomPK(models.Model): def __str__(self): return '%s: %s' % (self.my_pk, self.title) + class Editor(models.Model): name = models.CharField(max_length=100) + @python_2_unicode_compatible class BookWithOptionalAltEditor(models.Model): author = models.ForeignKey(Author) @@ -61,6 +66,7 @@ class BookWithOptionalAltEditor(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class AlternateBook(Book): notes = models.CharField(max_length=100) @@ -68,6 +74,7 @@ class AlternateBook(Book): def __str__(self): return '%s - %s' % (self.title, self.notes) + @python_2_unicode_compatible class AuthorMeeting(models.Model): name = models.CharField(max_length=100) @@ -77,6 +84,7 @@ class AuthorMeeting(models.Model): def __str__(self): return self.name + class CustomPrimaryKey(models.Model): my_pk = models.CharField(max_length=10, primary_key=True) some_field = models.CharField(max_length=100) @@ -84,6 +92,7 @@ class CustomPrimaryKey(models.Model): # models for inheritance tests. + @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=50) @@ -92,6 +101,7 @@ class Place(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Owner(models.Model): auto_id = models.AutoField(primary_key=True) @@ -101,12 +111,14 @@ class Owner(models.Model): def __str__(self): return "%s at %s" % (self.name, self.place) + class Location(models.Model): place = models.ForeignKey(Place, unique=True) # this is purely for testing the data doesn't matter here :) lat = models.CharField(max_length=100) lon = models.CharField(max_length=100) + @python_2_unicode_compatible class OwnerProfile(models.Model): owner = models.OneToOneField(Owner, primary_key=True) @@ -115,6 +127,7 @@ class OwnerProfile(models.Model): def __str__(self): return "%s is %d" % (self.owner.name, self.age) + @python_2_unicode_compatible class Restaurant(Place): serves_pizza = models.BooleanField(default=False) @@ -122,6 +135,7 @@ class Restaurant(Place): def __str__(self): return self.name + @python_2_unicode_compatible class Product(models.Model): slug = models.SlugField(unique=True) @@ -129,6 +143,7 @@ class Product(models.Model): def __str__(self): return self.slug + @python_2_unicode_compatible class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) @@ -140,13 +155,16 @@ class Price(models.Model): class Meta: unique_together = (('price', 'quantity'),) + class MexicanRestaurant(Restaurant): serves_tacos = models.BooleanField(default=False) + class ClassyMexicanRestaurant(MexicanRestaurant): restaurant = models.OneToOneField(MexicanRestaurant, parent_link=True, primary_key=True) tacos_are_yummy = models.BooleanField(default=False) + # models for testing unique_together validation when a fk is involved and # using inlineformset_factory. @python_2_unicode_compatible @@ -156,6 +174,7 @@ class Repository(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Revision(models.Model): repository = models.ForeignKey(Repository) @@ -167,21 +186,25 @@ class Revision(models.Model): def __str__(self): return "%s (%s)" % (self.revision, six.text_type(self.repository)) + # models for testing callable defaults (see bug #7975). If you define a model # with a callable default value, you cannot rely on the initial value in a # form. class Person(models.Model): name = models.CharField(max_length=128) + class Membership(models.Model): person = models.ForeignKey(Person) date_joined = models.DateTimeField(default=datetime.datetime.now) karma = models.IntegerField() + # models for testing a null=True fk to a parent class Team(models.Model): name = models.CharField(max_length=100) + @python_2_unicode_compatible class Player(models.Model): team = models.ForeignKey(Team, null=True) @@ -190,6 +213,7 @@ class Player(models.Model): def __str__(self): return self.name + # Models for testing custom ModelForm save methods in formsets and inline formsets @python_2_unicode_compatible class Poet(models.Model): @@ -198,6 +222,7 @@ class Poet(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Poem(models.Model): poet = models.ForeignKey(Poet) @@ -206,6 +231,7 @@ class Poem(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) diff --git a/tests/model_formsets_regress/models.py b/tests/model_formsets_regress/models.py index f94ad51929..58eed6a22b 100644 --- a/tests/model_formsets_regress/models.py +++ b/tests/model_formsets_regress/models.py @@ -6,23 +6,29 @@ class User(models.Model): username = models.CharField(max_length=12, unique=True) serial = models.IntegerField() + class UserSite(models.Model): user = models.ForeignKey(User, to_field="username") data = models.IntegerField() + class Place(models.Model): name = models.CharField(max_length=50) + class Restaurant(Place): pass + class Manager(models.Model): retaurant = models.ForeignKey(Restaurant) name = models.CharField(max_length=50) + class Network(models.Model): name = models.CharField(max_length=15) + @python_2_unicode_compatible class Host(models.Model): network = models.ForeignKey(Network) diff --git a/tests/model_formsets_regress/tests.py b/tests/model_formsets_regress/tests.py index f8a5b7b3ac..7d400d2f87 100644 --- a/tests/model_formsets_regress/tests.py +++ b/tests/model_formsets_regress/tests.py @@ -330,6 +330,7 @@ class FormfieldCallbackTests(TestCase): formfield_callback=callback) self.assertCallbackCalled(callback) + class BaseCustomDeleteFormSet(BaseFormSet): """ A formset mix-in that lets a form decide if it's to be deleted. diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py index 020bb35bc7..7f5702da59 100644 --- a/tests/model_inheritance/models.py +++ b/tests/model_inheritance/models.py @@ -20,6 +20,7 @@ from django.utils.encoding import python_2_unicode_compatible # Abstract base classes # + @python_2_unicode_compatible class CommonInfo(models.Model): name = models.CharField(max_length=50) @@ -32,18 +33,22 @@ class CommonInfo(models.Model): def __str__(self): return '%s %s' % (self.__class__.__name__, self.name) + class Worker(CommonInfo): job = models.CharField(max_length=50) + class Student(CommonInfo): school_class = models.CharField(max_length=10) class Meta: pass + class StudentWorker(Student, Worker): pass + # # Abstract base classes with related models # @@ -51,6 +56,7 @@ class StudentWorker(Student, Worker): class Post(models.Model): title = models.CharField(max_length=50) + @python_2_unicode_compatible class Attachment(models.Model): post = models.ForeignKey(Post, related_name='attached_%(class)s_set') @@ -62,12 +68,15 @@ class Attachment(models.Model): def __str__(self): return self.content + class Comment(Attachment): is_spam = models.BooleanField(default=False) + class Link(Attachment): url = models.URLField() + # # Multi-table inheritance # @@ -79,6 +88,7 @@ class Chef(models.Model): def __str__(self): return "%s the chef" % self.name + @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=50) @@ -87,6 +97,7 @@ class Place(models.Model): def __str__(self): return "%s the place" % self.name + class Rating(models.Model): rating = models.IntegerField(null=True, blank=True) @@ -94,6 +105,7 @@ class Rating(models.Model): abstract = True ordering = ['-rating'] + @python_2_unicode_compatible class Restaurant(Place, Rating): serves_hot_dogs = models.BooleanField(default=False) @@ -106,6 +118,7 @@ class Restaurant(Place, Rating): def __str__(self): return "%s the restaurant" % self.name + @python_2_unicode_compatible class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField(default=False) @@ -113,6 +126,7 @@ class ItalianRestaurant(Restaurant): def __str__(self): return "%s the italian restaurant" % self.name + @python_2_unicode_compatible class Supplier(Place): customers = models.ManyToManyField(Restaurant, related_name='provider') @@ -120,6 +134,7 @@ class Supplier(Place): def __str__(self): return "%s the supplier" % self.name + @python_2_unicode_compatible class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). @@ -129,6 +144,7 @@ class ParkingLot(Place): def __str__(self): return "%s the parking lot" % self.name + # # Abstract base classes with related models where the sub-class has the # same name in a different app and inherits from the same abstract base @@ -141,6 +157,7 @@ class ParkingLot(Place): class Title(models.Model): title = models.CharField(max_length=50) + class NamedURL(models.Model): title = models.ForeignKey(Title, related_name='attached_%(app_label)s_%(class)s_set') url = models.URLField() @@ -148,6 +165,7 @@ class NamedURL(models.Model): class Meta: abstract = True + @python_2_unicode_compatible class Copy(NamedURL): content = models.TextField() @@ -155,16 +173,20 @@ class Copy(NamedURL): def __str__(self): return self.content + class Mixin(object): def __init__(self): self.other_attr = 1 super(Mixin, self).__init__() + class MixinModel(models.Model, Mixin): pass + class Base(models.Model): titles = models.ManyToManyField(Title) + class SubBase(Base): sub_id = models.IntegerField(primary_key=True) diff --git a/tests/model_inheritance_regress/models.py b/tests/model_inheritance_regress/models.py index 04febf54a6..53752b6948 100644 --- a/tests/model_inheritance_regress/models.py +++ b/tests/model_inheritance_regress/models.py @@ -5,6 +5,7 @@ import datetime from django.db import models from django.utils.encoding import python_2_unicode_compatible + @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=50) @@ -16,6 +17,7 @@ class Place(models.Model): def __str__(self): return "%s the place" % self.name + @python_2_unicode_compatible class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) @@ -24,6 +26,7 @@ class Restaurant(Place): def __str__(self): return "%s the restaurant" % self.name + @python_2_unicode_compatible class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField(default=False) @@ -31,6 +34,7 @@ class ItalianRestaurant(Restaurant): def __str__(self): return "%s the italian restaurant" % self.name + @python_2_unicode_compatible class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). @@ -40,16 +44,19 @@ class ParkingLot(Place): def __str__(self): return "%s the parking lot" % self.name + class ParkingLot2(Place): # In lieu of any other connector, an existing OneToOneField will be # promoted to the primary key. parent = models.OneToOneField(Place) + class ParkingLot3(Place): # The parent_link connector need not be the pk on the model. primary_key = models.AutoField(primary_key=True) parent = models.OneToOneField(Place, parent_link=True) + class ParkingLot4(models.Model): # Test parent_link connector can be discovered in abstract classes. parent = models.OneToOneField(Place, parent_link=True) @@ -57,31 +64,40 @@ class ParkingLot4(models.Model): class Meta: abstract = True + class ParkingLot4A(ParkingLot4, Place): pass + class ParkingLot4B(Place, ParkingLot4): pass + class Supplier(models.Model): restaurant = models.ForeignKey(Restaurant) + class Wholesaler(Supplier): retailer = models.ForeignKey(Supplier, related_name='wholesale_supplier') + class Parent(models.Model): created = models.DateTimeField(default=datetime.datetime.now) + class Child(Parent): name = models.CharField(max_length=10) + class SelfRefParent(models.Model): parent_data = models.IntegerField() self_data = models.ForeignKey('self', null=True) + class SelfRefChild(SelfRefParent): child_data = models.IntegerField() + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) @@ -93,24 +109,30 @@ class Article(models.Model): def __str__(self): return self.headline + class ArticleWithAuthor(Article): author = models.CharField(max_length=100) + class M2MBase(models.Model): articles = models.ManyToManyField(Article) + class M2MChild(M2MBase): name = models.CharField(max_length=50) + class Evaluation(Article): quality = models.IntegerField() class Meta: abstract = True + class QualityControl(Evaluation): assignee = models.CharField(max_length=50) + @python_2_unicode_compatible class BaseM(models.Model): base_name = models.CharField(max_length=100) @@ -118,6 +140,7 @@ class BaseM(models.Model): def __str__(self): return self.base_name + @python_2_unicode_compatible class DerivedM(BaseM): customPK = models.IntegerField(primary_key=True) @@ -127,6 +150,7 @@ class DerivedM(BaseM): return "PK = %d, base_name = %s, derived_name = %s" % ( self.customPK, self.base_name, self.derived_name) + class AuditBase(models.Model): planned_date = models.DateField() @@ -134,13 +158,16 @@ class AuditBase(models.Model): abstract = True verbose_name_plural = 'Audits' + class CertificationAudit(AuditBase): class Meta(AuditBase.Meta): abstract = True + class InternalCertificationAudit(CertificationAudit): auditing_dept = models.CharField(max_length=20) + # Check that abstract classes don't get m2m tables autocreated. @python_2_unicode_compatible class Person(models.Model): @@ -152,6 +179,7 @@ class Person(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class AbstractEvent(models.Model): name = models.CharField(max_length=100) @@ -164,35 +192,44 @@ class AbstractEvent(models.Model): def __str__(self): return self.name + class BirthdayParty(AbstractEvent): pass + class BachelorParty(AbstractEvent): pass + class MessyBachelorParty(BachelorParty): pass + # Check concrete -> abstract -> concrete inheritance class SearchableLocation(models.Model): keywords = models.CharField(max_length=256) + class Station(SearchableLocation): name = models.CharField(max_length=128) class Meta: abstract = True + class BusStation(Station): bus_routes = models.CommaSeparatedIntegerField(max_length=128) inbound = models.BooleanField(default=False) + class TrainStation(Station): zone = models.IntegerField() + class User(models.Model): username = models.CharField(max_length=30, unique=True) + class Profile(User): profile_id = models.AutoField(primary_key=True) extra = models.CharField(max_length=30, blank=True) diff --git a/tests/model_inheritance_select_related/models.py b/tests/model_inheritance_select_related/models.py index 46c67cf07d..81f267589c 100644 --- a/tests/model_inheritance_select_related/models.py +++ b/tests/model_inheritance_select_related/models.py @@ -18,6 +18,7 @@ class Place(models.Model): def __str__(self): return "%s the place" % self.name + @python_2_unicode_compatible class Restaurant(Place): serves_sushi = models.BooleanField(default=False) @@ -26,6 +27,7 @@ class Restaurant(Place): def __str__(self): return "%s the restaurant" % self.name + @python_2_unicode_compatible class Person(models.Model): name = models.CharField(max_length=50) diff --git a/tests/model_validation/models.py b/tests/model_validation/models.py index d2e77cbccc..dfe6d62996 100644 --- a/tests/model_validation/models.py +++ b/tests/model_validation/models.py @@ -39,6 +39,7 @@ class ManyToManyRel(models.Model): # Models created as unmanaged as these aren't ever queried managed = False + class FKRel(models.Model): thing1 = models.ForeignKey(ThingWithIterableChoices, related_name='+') thing2 = models.ForeignKey(ThingWithIterableChoices, related_name='+') diff --git a/tests/modeladmin/models.py b/tests/modeladmin/models.py index 27f54821d6..8f57a9fa82 100644 --- a/tests/modeladmin/models.py +++ b/tests/modeladmin/models.py @@ -16,6 +16,7 @@ class Band(models.Model): def __str__(self): return self.name + class Concert(models.Model): main_band = models.ForeignKey(Band, related_name='main_concerts') opening_band = models.ForeignKey(Band, related_name='opening_concerts', @@ -27,6 +28,7 @@ class Concert(models.Model): (3, 'Bus') ), blank=True) + class ValidationTestModel(models.Model): name = models.CharField(max_length=100) slug = models.SlugField() @@ -40,5 +42,6 @@ class ValidationTestModel(models.Model): def decade_published_in(self): return self.pub_date.strftime('%Y')[:3] + "0's" + class ValidationTestInlineModel(models.Model): parent = models.ForeignKey(ValidationTestModel) diff --git a/tests/multiple_database/models.py b/tests/multiple_database/models.py index 00534c870c..fc5b28ad92 100644 --- a/tests/multiple_database/models.py +++ b/tests/multiple_database/models.py @@ -18,10 +18,12 @@ class Review(models.Model): class Meta: ordering = ('source',) + class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) + @python_2_unicode_compatible class Person(models.Model): objects = PersonManager() @@ -33,6 +35,7 @@ class Person(models.Model): class Meta: ordering = ('name',) + # This book manager doesn't do anything interesting; it just # exists to strip out the 'extra_arg' argument to certain # calls. This argument is used to establish that the BookManager @@ -46,6 +49,7 @@ class BookManager(models.Manager): kwargs.pop('extra_arg', None) return super(BookManager, self).get_or_create(*args, **kwargs) + @python_2_unicode_compatible class Book(models.Model): objects = BookManager() @@ -62,6 +66,7 @@ class Book(models.Model): class Meta: ordering = ('title',) + @python_2_unicode_compatible class Pet(models.Model): name = models.CharField(max_length=100) @@ -73,6 +78,7 @@ class Pet(models.Model): class Meta: ordering = ('name',) + class UserProfile(models.Model): user = models.OneToOneField(User, null=True) flavor = models.CharField(max_length=100) -- cgit v1.3 From 7a61c68c50d3837c50e35c252fd76220f08b5290 Mon Sep 17 00:00:00 2001 From: Jason Myers Date: Sat, 2 Nov 2013 23:36:09 -0500 Subject: PEP8 cleanup Signed-off-by: Jason Myers --- tests/admin_changelist/models.py | 15 ++ tests/admin_custom_urls/models.py | 2 + tests/admin_docs/views.py | 2 + tests/admin_filters/models.py | 1 + tests/admin_inlines/admin.py | 3 + tests/admin_inlines/models.py | 21 +++ tests/admin_inlines/tests.py | 24 +-- tests/admin_ordering/models.py | 4 + tests/admin_ordering/tests.py | 1 + tests/admin_scripts/tests.py | 9 ++ tests/admin_util/models.py | 5 + tests/admin_util/tests.py | 6 +- tests/admin_validation/tests.py | 3 + tests/admin_views/models.py | 22 +++ tests/admin_views/tests.py | 35 ++--- tests/admin_views/views.py | 1 + tests/admin_widgets/models.py | 14 ++ tests/admin_widgets/tests.py | 16 +- tests/aggregation/models.py | 3 + tests/aggregation_regress/models.py | 6 +- tests/backends/tests.py | 18 ++- tests/basic/models.py | 2 + tests/basic/tests.py | 48 ++++-- tests/bug639/models.py | 2 + tests/bulk_create/models.py | 5 + tests/cache/closeable_cache.py | 1 + tests/cache/liberal_backend.py | 1 + tests/cache/models.py | 1 + tests/cache/tests.py | 6 + tests/check/models.py | 2 + tests/check/tests.py | 1 + tests/choices/models.py | 1 + tests/commands_sql/tests.py | 1 + tests/conditional_processing/tests.py | 1 + tests/conditional_processing/views.py | 4 + tests/contenttypes_tests/models.py | 2 + tests/contenttypes_tests/tests.py | 1 + tests/csrf_tests/tests.py | 5 + tests/custom_columns/models.py | 1 + tests/custom_columns_regress/models.py | 1 + tests/custom_columns_regress/tests.py | 1 + tests/custom_managers/models.py | 10 ++ tests/custom_managers_regress/models.py | 3 + tests/custom_pk/fields.py | 1 + tests/custom_pk/models.py | 4 +- tests/datatypes/models.py | 1 + tests/dates/models.py | 2 + tests/datetimes/models.py | 2 + tests/db_typecasts/tests.py | 1 + tests/defer_regress/tests.py | 1 + tests/delete/models.py | 6 + tests/delete/tests.py | 3 +- tests/delete_regress/models.py | 28 ++++ tests/delete_regress/tests.py | 3 +- tests/dispatch/tests/test_dispatcher.py | 8 +- tests/dispatch/tests/test_saferef.py | 4 + tests/distinct_on_fields/models.py | 5 + tests/distinct_on_fields/tests.py | 3 +- tests/expressions/models.py | 1 + tests/expressions_regress/models.py | 1 + tests/expressions_regress/tests.py | 70 ++++----- tests/extra_regress/models.py | 2 + tests/field_subclassing/fields.py | 2 + tests/field_subclassing/models.py | 2 + tests/file_storage/models.py | 1 + tests/file_storage/tests.py | 5 + tests/file_uploads/tests.py | 3 +- tests/file_uploads/uploadhandler.py | 4 +- tests/file_uploads/views.py | 10 ++ tests/fixtures/models.py | 8 + tests/fixtures_model_package/models/__init__.py | 1 + tests/fixtures_regress/models.py | 1 + tests/force_insert_update/models.py | 4 + tests/foreign_object/models.py | 11 ++ tests/foreign_object/tests.py | 2 + tests/forms_tests/models.py | 5 +- tests/forms_tests/tests/test_error_messages.py | 1 + tests/forms_tests/tests/test_extra.py | 3 + tests/forms_tests/tests/test_formsets.py | 6 +- tests/forms_tests/tests/test_input_formats.py | 2 + tests/forms_tests/tests/test_widgets.py | 4 +- tests/forms_tests/tests/tests.py | 1 + tests/generic_inline_admin/admin.py | 1 + tests/generic_inline_admin/models.py | 2 + tests/generic_inline_admin/tests.py | 3 + tests/generic_relations/tests.py | 2 + tests/generic_relations_regress/models.py | 25 +++ tests/generic_views/models.py | 4 + tests/generic_views/test_base.py | 1 + tests/generic_views/test_dates.py | 3 +- tests/generic_views/views.py | 19 +++ tests/get_object_or_404/models.py | 2 + tests/get_or_create_regress/models.py | 2 + tests/handlers/views.py | 5 + tests/httpwrappers/tests.py | 5 + tests/i18n/forms.py | 2 + tests/i18n/models.py | 1 + tests/i18n/test_extraction.py | 18 ++- tests/i18n/tests.py | 3 + tests/inline_formsets/models.py | 4 + tests/inspectdb/models.py | 6 + tests/inspectdb/tests.py | 3 +- tests/known_related_objects/models.py | 4 + tests/known_related_objects/tests.py | 1 + tests/logging_tests/tests.py | 2 + tests/lookup/models.py | 5 + tests/m2m_and_m2o/models.py | 2 + tests/m2m_and_m2o/tests.py | 3 +- tests/m2m_intermediary/models.py | 2 + tests/m2m_regress/models.py | 9 ++ tests/m2m_signals/models.py | 3 + tests/m2m_through/models.py | 6 + tests/m2m_through_regress/models.py | 9 ++ tests/m2o_recursive/models.py | 1 + tests/m2o_recursive/tests.py | 1 + tests/many_to_many/models.py | 1 + tests/many_to_one/models.py | 1 + tests/many_to_one_null/models.py | 1 + tests/many_to_one_regress/models.py | 11 +- tests/max_lengths/models.py | 1 + tests/max_lengths/tests.py | 1 + tests/middleware/tests.py | 12 +- tests/middleware_exceptions/tests.py | 2 + tests/middleware_exceptions/views.py | 6 + tests/model_fields/tests.py | 8 + tests/model_forms/models.py | 28 ++++ tests/model_inheritance_same_model_name/models.py | 1 + tests/multiple_database/tests.py | 180 ++++++++++++---------- 128 files changed, 739 insertions(+), 206 deletions(-) (limited to 'tests/multiple_database') diff --git a/tests/admin_changelist/models.py b/tests/admin_changelist/models.py index 242e4b7b6c..76249b2cd3 100644 --- a/tests/admin_changelist/models.py +++ b/tests/admin_changelist/models.py @@ -1,26 +1,32 @@ from django.db import models from django.utils.encoding import python_2_unicode_compatible + class Event(models.Model): # Oracle can have problems with a column named "date" date = models.DateField(db_column="event_date") + class Parent(models.Model): name = models.CharField(max_length=128) + class Child(models.Model): parent = models.ForeignKey(Parent, editable=False, null=True) name = models.CharField(max_length=30, blank=True) age = models.IntegerField(null=True, blank=True) + class Genre(models.Model): name = models.CharField(max_length=20) + class Band(models.Model): name = models.CharField(max_length=20) nr_of_members = models.PositiveIntegerField() genres = models.ManyToManyField(Genre) + @python_2_unicode_compatible class Musician(models.Model): name = models.CharField(max_length=30) @@ -28,6 +34,7 @@ class Musician(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Group(models.Model): name = models.CharField(max_length=30) @@ -36,26 +43,32 @@ class Group(models.Model): def __str__(self): return self.name + class Membership(models.Model): music = models.ForeignKey(Musician) group = models.ForeignKey(Group) role = models.CharField(max_length=15) + class Quartet(Group): pass + class ChordsMusician(Musician): pass + class ChordsBand(models.Model): name = models.CharField(max_length=30) members = models.ManyToManyField(ChordsMusician, through='Invitation') + class Invitation(models.Model): player = models.ForeignKey(ChordsMusician) band = models.ForeignKey(ChordsBand) instrument = models.CharField(max_length=15) + class Swallow(models.Model): origin = models.CharField(max_length=255) load = models.FloatField() @@ -77,6 +90,7 @@ class OrderedObjectManager(models.Manager): def get_queryset(self): return super(OrderedObjectManager, self).get_queryset().order_by('number') + class OrderedObject(models.Model): """ Model with Manager that defines a default order. @@ -88,5 +102,6 @@ class OrderedObject(models.Model): objects = OrderedObjectManager() + class CustomIdUser(models.Model): uuid = models.AutoField(primary_key=True) diff --git a/tests/admin_custom_urls/models.py b/tests/admin_custom_urls/models.py index 55fc064835..121e03b860 100644 --- a/tests/admin_custom_urls/models.py +++ b/tests/admin_custom_urls/models.py @@ -54,6 +54,7 @@ class ActionAdmin(admin.ModelAdmin): class Person(models.Model): name = models.CharField(max_length=20) + class PersonAdmin(admin.ModelAdmin): def response_post_save_add(self, request, obj): @@ -68,6 +69,7 @@ class PersonAdmin(admin.ModelAdmin): class Car(models.Model): name = models.CharField(max_length=20) + class CarAdmin(admin.ModelAdmin): def response_add(self, request, obj, post_url_continue=None): diff --git a/tests/admin_docs/views.py b/tests/admin_docs/views.py index e47177c37f..9a2f81d45c 100644 --- a/tests/admin_docs/views.py +++ b/tests/admin_docs/views.py @@ -5,9 +5,11 @@ from django.contrib.admindocs.middleware import XViewMiddleware xview_dec = decorator_from_middleware(XViewMiddleware) + def xview(request): return HttpResponse() + class XViewClass(View): def get(self, request): return HttpResponse() diff --git a/tests/admin_filters/models.py b/tests/admin_filters/models.py index bd2e4e5e98..4634ebb535 100644 --- a/tests/admin_filters/models.py +++ b/tests/admin_filters/models.py @@ -27,6 +27,7 @@ class Department(models.Model): def __str__(self): return self.description + @python_2_unicode_compatible class Employee(models.Model): department = models.ForeignKey(Department, to_field="code") diff --git a/tests/admin_inlines/admin.py b/tests/admin_inlines/admin.py index da5ddc03b3..b46a045052 100644 --- a/tests/admin_inlines/admin.py +++ b/tests/admin_inlines/admin.py @@ -153,6 +153,7 @@ class ChildModel1Inline(admin.TabularInline): class ChildModel2Inline(admin.StackedInline): model = ChildModel2 + # admin for #19425 and #18388 class BinaryTreeAdmin(admin.TabularInline): model = BinaryTree @@ -169,10 +170,12 @@ class BinaryTreeAdmin(admin.TabularInline): return max_num - obj.binarytree_set.count() return max_num + # admin for #19524 class SightingInline(admin.TabularInline): model = Sighting + # admin and form for #18263 class SomeChildModelForm(forms.ModelForm): diff --git a/tests/admin_inlines/models.py b/tests/admin_inlines/models.py index 36e9e8e54d..d4374ec14b 100644 --- a/tests/admin_inlines/models.py +++ b/tests/admin_inlines/models.py @@ -89,6 +89,7 @@ class Inner2(models.Model): dummy = models.IntegerField() holder = models.ForeignKey(Holder2) + class Holder3(models.Model): dummy = models.IntegerField() @@ -99,38 +100,47 @@ class Inner3(models.Model): # Models for ticket #8190 + class Holder4(models.Model): dummy = models.IntegerField() + class Inner4Stacked(models.Model): dummy = models.IntegerField(help_text="Awesome stacked help text is awesome.") holder = models.ForeignKey(Holder4) + class Inner4Tabular(models.Model): dummy = models.IntegerField(help_text="Awesome tabular help text is awesome.") holder = models.ForeignKey(Holder4) # Models for #12749 + class Person(models.Model): firstname = models.CharField(max_length=15) + class OutfitItem(models.Model): name = models.CharField(max_length=15) + class Fashionista(models.Model): person = models.OneToOneField(Person, primary_key=True) weaknesses = models.ManyToManyField(OutfitItem, through='ShoppingWeakness', blank=True) + class ShoppingWeakness(models.Model): fashionista = models.ForeignKey(Fashionista) item = models.ForeignKey(OutfitItem) # Models for #13510 + class TitleCollection(models.Model): pass + class Title(models.Model): collection = models.ForeignKey(TitleCollection, blank=True, null=True) title1 = models.CharField(max_length=100) @@ -138,19 +148,24 @@ class Title(models.Model): # Models for #15424 + class Poll(models.Model): name = models.CharField(max_length=40) + class Question(models.Model): poll = models.ForeignKey(Poll) + class Novel(models.Model): name = models.CharField(max_length=40) + class Chapter(models.Model): name = models.CharField(max_length=40) novel = models.ForeignKey(Novel) + class FootNote(models.Model): """ Model added for ticket 19838 @@ -160,6 +175,7 @@ class FootNote(models.Model): # Models for #16838 + class CapoFamiglia(models.Model): name = models.CharField(max_length=100) @@ -211,12 +227,15 @@ class BinaryTree(models.Model): # Models for #19524 + class LifeForm(models.Model): pass + class ExtraTerrestrial(LifeForm): name = models.CharField(max_length=100) + class Sighting(models.Model): et = models.ForeignKey(ExtraTerrestrial) place = models.CharField(max_length=100) @@ -234,9 +253,11 @@ class SomeChildModel(models.Model): # Other models + class ProfileCollection(models.Model): pass + class Profile(models.Model): collection = models.ForeignKey(ProfileCollection, blank=True, null=True) first_name = models.CharField(max_length=100) diff --git a/tests/admin_inlines/tests.py b/tests/admin_inlines/tests.py index 2d0a7edd10..8d6fc97426 100644 --- a/tests/admin_inlines/tests.py +++ b/tests/admin_inlines/tests.py @@ -279,6 +279,7 @@ class TestInlineMedia(TestCase): self.assertContains(response, 'my_awesome_admin_scripts.js') self.assertContains(response, 'my_awesome_inline_scripts.js') + class TestInlineAdminForm(TestCase): urls = "admin_inlines.urls" @@ -465,9 +466,9 @@ class TestInlinePermissions(TestCase): self.assertContains(response, 'Add another Inner2') # 3 extra forms only, not the existing instance form self.assertContains(response, '', html=True) + 'value="3" name="inner2_set-TOTAL_FORMS" />', html=True) self.assertNotContains(response, '' % self.inner2_id, html=True) + 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) def test_inline_change_fk_change_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) @@ -477,12 +478,12 @@ class TestInlinePermissions(TestCase): self.assertContains(response, '

    Inner2s

    ') # Just the one form for existing instances self.assertContains(response, '', html=True) + 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) self.assertContains(response, '' % self.inner2_id, html=True) + 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) # max-num 0 means we can't add new ones self.assertContains(response, '', html=True) + 'value="0" name="inner2_set-MAX_NUM_FORMS" />', html=True) def test_inline_change_fk_add_change_perm(self): permission = Permission.objects.get(codename='add_inner2', content_type=self.inner_ct) @@ -494,9 +495,9 @@ class TestInlinePermissions(TestCase): self.assertContains(response, '

    Inner2s

    ') # One form for existing instance and three extra for new self.assertContains(response, '', html=True) + 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) self.assertContains(response, '' % self.inner2_id, html=True) + 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) def test_inline_change_fk_change_del_perm(self): permission = Permission.objects.get(codename='change_inner2', content_type=self.inner_ct) @@ -508,9 +509,9 @@ class TestInlinePermissions(TestCase): self.assertContains(response, '

    Inner2s

    ') # One form for existing instance only, no new self.assertContains(response, '', html=True) + 'value="1" name="inner2_set-TOTAL_FORMS" />', html=True) self.assertContains(response, '' % self.inner2_id, html=True) + 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') def test_inline_change_fk_all_perms(self): @@ -525,9 +526,9 @@ class TestInlinePermissions(TestCase): self.assertContains(response, '

    Inner2s

    ') # One form for existing instance only, three for new self.assertContains(response, '', html=True) + 'value="4" name="inner2_set-TOTAL_FORMS" />', html=True) self.assertContains(response, '' % self.inner2_id, html=True) + 'value="%i" name="inner2_set-0-id" />' % self.inner2_id, html=True) self.assertContains(response, 'id="id_inner2_set-0-DELETE"') @@ -698,5 +699,6 @@ class SeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): class SeleniumChromeTests(SeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class SeleniumIETests(SeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' diff --git a/tests/admin_ordering/models.py b/tests/admin_ordering/models.py index 3da52b1b00..fb99d2dac5 100644 --- a/tests/admin_ordering/models.py +++ b/tests/admin_ordering/models.py @@ -11,6 +11,7 @@ class Band(models.Model): class Meta: ordering = ('name',) + class Song(models.Model): band = models.ForeignKey(Band) name = models.CharField(max_length=100) @@ -20,13 +21,16 @@ class Song(models.Model): class Meta: ordering = ('name',) + class SongInlineDefaultOrdering(admin.StackedInline): model = Song + class SongInlineNewOrdering(admin.StackedInline): model = Song ordering = ('duration', ) + class DynOrderingBandAdmin(admin.ModelAdmin): def get_ordering(self, request): diff --git a/tests/admin_ordering/tests.py b/tests/admin_ordering/tests.py index 0085b35586..e58e3b5abf 100644 --- a/tests/admin_ordering/tests.py +++ b/tests/admin_ordering/tests.py @@ -12,6 +12,7 @@ from .models import (Band, Song, SongInlineDefaultOrdering, class MockRequest(object): pass + class MockSuperUser(object): def has_perm(self, perm): return True diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index dae1314982..73a91b6e7b 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -289,6 +289,7 @@ class DjangoAdminDefaultSettings(AdminScriptTestCase): self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") + class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that contains the test application specified using a full path. @@ -355,6 +356,7 @@ class DjangoAdminFullPathDefaultSettings(AdminScriptTestCase): self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") + class DjangoAdminMinimalSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings.py file that doesn't contain the test application. @@ -421,6 +423,7 @@ class DjangoAdminMinimalSettings(AdminScriptTestCase): self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") + class DjangoAdminAlternateSettings(AdminScriptTestCase): """A series of tests for django-admin.py when using a settings file with a name other than 'settings.py'. @@ -796,6 +799,7 @@ class ManageFullPathDefaultSettings(AdminScriptTestCase): self.assertNoOutput(err) self.assertOutput(out, "EXECUTE:NoArgsCommand") + class ManageMinimalSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings.py file that doesn't contain the test application. @@ -862,6 +866,7 @@ class ManageMinimalSettings(AdminScriptTestCase): self.assertNoOutput(out) self.assertOutput(err, "Unknown command: 'noargs_command'") + class ManageAlternateSettings(AdminScriptTestCase): """A series of tests for manage.py when using a settings file with a name other than 'settings.py'. @@ -1121,6 +1126,7 @@ class CustomTestRunner(DiscoverRunner): def run_tests(self, test_labels, extra_tests=None, **kwargs): pass + class ManageTestCommand(AdminScriptTestCase): def setUp(self): from django.core.management.commands.test import Command as TestCommand @@ -1214,6 +1220,7 @@ class ManageRunserver(AdminScriptTestCase): self.cmd.handle(addrport="deadbeef:7654") self.assertServerSettings('deadbeef', '7654') + class ManageRunserverEmptyAllowedHosts(AdminScriptTestCase): def setUp(self): self.write_settings('settings.py', sdict={ @@ -1464,6 +1471,7 @@ class CommandTypes(AdminScriptTestCase): self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=testlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]")) self.assertOutput(out, str_prefix("EXECUTE:LabelCommand label=anotherlabel, options=[('no_color', False), ('pythonpath', None), ('settings', None), ('traceback', None), ('verbosity', %(_)s'1')]")) + class ArgumentOrder(AdminScriptTestCase): """Tests for 2-stage argument parsing scheme. @@ -1751,6 +1759,7 @@ class DiffSettings(AdminScriptTestCase): self.assertNoOutput(err) self.assertOutput(out, "### STATIC_URL = None") + class Dumpdata(AdminScriptTestCase): """Tests for dumpdata management command.""" diff --git a/tests/admin_util/models.py b/tests/admin_util/models.py index 32a6cd6291..5e86f55a3a 100644 --- a/tests/admin_util/models.py +++ b/tests/admin_util/models.py @@ -19,6 +19,7 @@ class Article(models.Model): return "nothing" test_from_model_with_override.short_description = "not What you Expect" + @python_2_unicode_compatible class Count(models.Model): num = models.PositiveSmallIntegerField() @@ -27,12 +28,15 @@ class Count(models.Model): def __str__(self): return six.text_type(self.num) + class Event(models.Model): date = models.DateTimeField(auto_now_add=True) + class Location(models.Model): event = models.OneToOneField(Event, verbose_name='awesome event') + class Guest(models.Model): event = models.OneToOneField(Event) name = models.CharField(max_length=255) @@ -40,5 +44,6 @@ class Guest(models.Model): class Meta: verbose_name = "awesome guest" + class EventGuide(models.Model): event = models.ForeignKey(Event, on_delete=models.DO_NOTHING) diff --git a/tests/admin_util/tests.py b/tests/admin_util/tests.py index 915dfced08..b978a4ab05 100644 --- a/tests/admin_util/tests.py +++ b/tests/admin_util/tests.py @@ -80,6 +80,7 @@ class NestedObjectsTests(TestCase): # One for Location, one for Guest, and no query for EventGuide n.collect(objs) + class UtilTests(SimpleTestCase): def test_values_from_lookup_field(self): """ @@ -228,9 +229,8 @@ class UtilTests(SimpleTestCase): ) self.assertEqual( label_for_field("test_from_model", Article, - model_admin = MockModelAdmin, - return_attr = True - ), + model_admin=MockModelAdmin, + return_attr=True), ("not Really the Model", MockModelAdmin.test_from_model) ) diff --git a/tests/admin_validation/tests.py b/tests/admin_validation/tests.py index f1346647ee..5e38af82f0 100644 --- a/tests/admin_validation/tests.py +++ b/tests/admin_validation/tests.py @@ -12,10 +12,12 @@ from .models import Song, Book, Album, TwoAlbumFKAndAnE, City class SongForm(forms.ModelForm): pass + class ValidFields(admin.ModelAdmin): form = SongForm fields = ['title'] + class ValidFormFieldsets(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): class ExtraFieldForm(SongForm): @@ -28,6 +30,7 @@ class ValidFormFieldsets(admin.ModelAdmin): }), ) + class ValidationTestCase(TestCase): def test_readonly_and_editable(self): diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py index 4dcca9a4cb..e2b6a00261 100644 --- a/tests/admin_views/models.py +++ b/tests/admin_views/models.py @@ -120,11 +120,13 @@ class Color(models.Model): def __str__(self): return self.value + # we replicate Color to register with another ModelAdmin class Color2(Color): class Meta: proxy = True + @python_2_unicode_compatible class Thing(models.Model): title = models.CharField(max_length=20) @@ -613,10 +615,12 @@ class PrePopulatedPostLargeSlug(models.Model): published = models.BooleanField(default=False) slug = models.SlugField(max_length=1000) + class AdminOrderedField(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) + class AdminOrderedModelMethod(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) @@ -625,14 +629,17 @@ class AdminOrderedModelMethod(models.Model): return self.order some_order.admin_order_field = 'order' + class AdminOrderedAdminMethod(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) + class AdminOrderedCallable(models.Model): order = models.IntegerField() stuff = models.CharField(max_length=200) + @python_2_unicode_compatible class Report(models.Model): title = models.CharField(max_length=100) @@ -651,6 +658,7 @@ class MainPrepopulated(models.Model): slug1 = models.SlugField(blank=True) slug2 = models.SlugField(blank=True) + class RelatedPrepopulated(models.Model): parent = models.ForeignKey(MainPrepopulated) name = models.CharField(max_length=75) @@ -671,6 +679,7 @@ class UnorderedObject(models.Model): name = models.CharField(max_length=255) bool = models.BooleanField(default=True) + class UndeletableObject(models.Model): """ Model whose show_delete in admin change_view has been disabled @@ -678,30 +687,36 @@ class UndeletableObject(models.Model): """ name = models.CharField(max_length=255) + class UnchangeableObject(models.Model): """ Model whose change_view is disabled in admin Refs #20640. """ + class UserMessenger(models.Model): """ Dummy class for testing message_user functions on ModelAdmin """ + class Simple(models.Model): """ Simple model with nothing on it for use in testing """ + class Choice(models.Model): choice = models.IntegerField(blank=True, null=True, choices=((1, 'Yes'), (0, 'No'), (None, 'No opinion'))) + class _Manager(models.Manager): def get_queryset(self): return super(_Manager, self).get_queryset().filter(pk__gt=1) + class FilteredManager(models.Model): def __str__(self): return "PK=%d" % self.pk @@ -709,26 +724,33 @@ class FilteredManager(models.Model): pk_gt_1 = _Manager() objects = models.Manager() + class EmptyModelVisible(models.Model): """ See ticket #11277. """ + class EmptyModelHidden(models.Model): """ See ticket #11277. """ + class EmptyModelMixin(models.Model): """ See ticket #11277. """ + class State(models.Model): name = models.CharField(max_length=100) + class City(models.Model): state = models.ForeignKey(State) name = models.CharField(max_length=100) + class Restaurant(models.Model): city = models.ForeignKey(City) name = models.CharField(max_length=100) + class Worker(models.Model): work_at = models.ForeignKey(Restaurant) name = models.CharField(max_length=50) diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index 91af9521a3..0ec9f25479 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -84,8 +84,8 @@ class AdminViewBasicTestCase(TestCase): """ self.assertEqual(response.status_code, 200) self.assertTrue(response.content.index(force_bytes(text1)) < response.content.index(force_bytes(text2)), - failing_msg - ) + failing_msg) + class AdminViewBasicTest(AdminViewBasicTestCase): def testTrailingSlashRequired(self): @@ -94,8 +94,8 @@ class AdminViewBasicTest(AdminViewBasicTestCase): """ response = self.client.get('/test_admin/%s/admin_views/article/add' % self.urlbit) self.assertRedirects(response, - '/test_admin/%s/admin_views/article/add/' % self.urlbit, status_code=301 - ) + '/test_admin/%s/admin_views/article/add/' % self.urlbit, + status_code=301) def testBasicAddGet(self): """ @@ -109,8 +109,7 @@ class AdminViewBasicTest(AdminViewBasicTestCase): response = self.client.get('/test_admin/%s/admin_views/section/add/' % self.urlbit, {'name': 'My Section'}) self.assertEqual(response.status_code, 200) self.assertContains(response, 'value="My Section"', - msg_prefix="Couldn't find an input with the right value in the response" - ) + msg_prefix="Couldn't find an input with the right value in the response") def testBasicEditGet(self): """ @@ -394,11 +393,9 @@ class AdminViewBasicTest(AdminViewBasicTestCase): response = self.client.get('/test_admin/%s/admin_views/thing/' % self.urlbit) self.assertEqual(response.status_code, 200) self.assertContains(response, '
    ', - msg_prefix="Expected filter not found in changelist view" - ) + msg_prefix="Expected filter not found in changelist view") self.assertNotContains(response, 'Blue', - msg_prefix="Changelist filter not correctly limited by limit_choices_to" - ) + msg_prefix="Changelist filter not correctly limited by limit_choices_to") def testRelationSpanningFilters(self): response = self.client.get('/test_admin/%s/admin_views/chapterxtra1/' % @@ -1557,7 +1554,7 @@ class AdminViewStringPrimaryKeyTest(TestCase): response = self.client.get('/test_admin/admin/') counted_presence_after = response.content.count(force_bytes(should_contain)) self.assertEqual(counted_presence_before - 1, - counted_presence_after) + counted_presence_after) def test_logentry_get_admin_url(self): "LogEntry.get_admin_url returns a URL to edit the entry's object or None for non-existent (possibly deleted) models" @@ -1612,13 +1609,13 @@ class AdminViewStringPrimaryKeyTest(TestCase): def test_change_view_history_link(self): """Object history button link should work and contain the pk value quoted.""" url = reverse('admin:%s_modelwithstringprimarykey_change' % - ModelWithStringPrimaryKey._meta.app_label, - args=(quote(self.pk),)) + ModelWithStringPrimaryKey._meta.app_label, + args=(quote(self.pk),)) response = self.client.get(url) self.assertEqual(response.status_code, 200) expected_link = reverse('admin:%s_modelwithstringprimarykey_history' % - ModelWithStringPrimaryKey._meta.app_label, - args=(quote(self.pk),)) + ModelWithStringPrimaryKey._meta.app_label, + args=(quote(self.pk),)) self.assertContains(response, ' response = self.client.get('/test_admin/admin/admin_views/oldsubscriber/') self.assertEqual(response.context["action_form"], None) self.assertContains(response, 'jquery.min.js', - msg_prefix="jQuery missing from admin pages for model with no admin actions" - ) + msg_prefix="jQuery missing from admin pages for model with no admin actions") def test_action_column_class(self): "Tests that the checkbox column class is present in the response" @@ -3631,8 +3627,7 @@ class ReadonlyTest(TestCase): self.assertContains(response, "InlineMultiline
    test
    string") self.assertContains(response, - formats.localize(datetime.date.today() - datetime.timedelta(days=7)) - ) + formats.localize(datetime.date.today() - datetime.timedelta(days=7))) self.assertContains(response, '
    ') self.assertContains(response, '
    ') @@ -3829,7 +3824,7 @@ class UserAdminTest(TestCase): adminform = response.context['adminform'] self.assertTrue('password' not in adminform.form.errors) self.assertEqual(adminform.form.errors['password2'], - ["The two password fields didn't match."]) + ["The two password fields didn't match."]) def test_user_fk_popup(self): """Quick user addition in a FK popup shouldn't invoke view for further user customization""" diff --git a/tests/admin_views/views.py b/tests/admin_views/views.py index bb5f24ebfe..cfae496aba 100644 --- a/tests/admin_views/views.py +++ b/tests/admin_views/views.py @@ -1,6 +1,7 @@ from django.contrib.admin.views.decorators import staff_member_required from django.http import HttpResponse + @staff_member_required def secure_view(request): return HttpResponse('%s' % request.POST) diff --git a/tests/admin_widgets/models.py b/tests/admin_widgets/models.py index 6a6c6e096b..5d295f0c9b 100644 --- a/tests/admin_widgets/models.py +++ b/tests/admin_widgets/models.py @@ -8,6 +8,7 @@ from django.utils.encoding import python_2_unicode_compatible class MyFileField(models.FileField): pass + @python_2_unicode_compatible class Member(models.Model): name = models.CharField(max_length=100) @@ -18,6 +19,7 @@ class Member(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Band(models.Model): name = models.CharField(max_length=100) @@ -27,6 +29,7 @@ class Band(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Album(models.Model): band = models.ForeignKey(Band) @@ -37,10 +40,12 @@ class Album(models.Model): def __str__(self): return self.name + class HiddenInventoryManager(models.Manager): def get_queryset(self): return super(HiddenInventoryManager, self).get_queryset().filter(hidden=False) + @python_2_unicode_compatible class Inventory(models.Model): barcode = models.PositiveIntegerField(unique=True) @@ -55,6 +60,7 @@ class Inventory(models.Model): def __str__(self): return self.name + class Event(models.Model): main_band = models.ForeignKey(Band, limit_choices_to=models.Q(pk__gt=0), related_name='events_main_band_at') supporting_bands = models.ManyToManyField(Band, null=True, blank=True, related_name='events_supporting_band_at') @@ -64,6 +70,7 @@ class Event(models.Model): link = models.URLField(blank=True) min_age = models.IntegerField(blank=True, null=True) + @python_2_unicode_compatible class Car(models.Model): owner = models.ForeignKey(User) @@ -73,15 +80,18 @@ class Car(models.Model): def __str__(self): return "%s %s" % (self.make, self.model) + class CarTire(models.Model): """ A single car tire. This to test that a user can only select their own cars. """ car = models.ForeignKey(Car) + class Honeycomb(models.Model): location = models.CharField(max_length=20) + class Bee(models.Model): """ A model with a FK to a model that won't be registered with the admin @@ -90,6 +100,7 @@ class Bee(models.Model): """ honeycomb = models.ForeignKey(Honeycomb) + class Individual(models.Model): """ A model with a FK to itself. It won't be registered with the admin, so the @@ -99,9 +110,11 @@ class Individual(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey('self', null=True) + class Company(models.Model): name = models.CharField(max_length=20) + class Advisor(models.Model): """ A model with a m2m to a model that won't be registered with the admin @@ -122,6 +135,7 @@ class Student(models.Model): class Meta: ordering = ('name',) + @python_2_unicode_compatible class School(models.Model): name = models.CharField(max_length=255) diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py index 4b36f8bd32..0dec3a2cfa 100644 --- a/tests/admin_widgets/tests.py +++ b/tests/admin_widgets/tests.py @@ -25,6 +25,7 @@ admin_static_prefix = lambda: { 'ADMIN_STATIC_PREFIX': "%sadmin/" % settings.STATIC_URL, } + class AdminFormfieldForDBFieldTests(TestCase): """ Tests for correct behavior of ModelAdmin.formfield_for_dbfield @@ -269,6 +270,7 @@ class FilteredSelectMultipleWidgetTest(DjangoTestCase): '\n' % admin_static_prefix() ) + class AdminDateWidgetTest(DjangoTestCase): def test_attrs(self): """ @@ -287,6 +289,7 @@ class AdminDateWidgetTest(DjangoTestCase): '', ) + class AdminTimeWidgetTest(DjangoTestCase): def test_attrs(self): """ @@ -305,6 +308,7 @@ class AdminTimeWidgetTest(DjangoTestCase): '', ) + class AdminSplitDateTimeWidgetTest(DjangoTestCase): def test_render(self): w = widgets.AdminSplitDateTime() @@ -495,6 +499,7 @@ class ManyToManyRawIdWidgetTest(DjangoTestCase): '' % {'c1pk': c1.pk} ) + class RelatedFieldWidgetWrapperTests(DjangoTestCase): def test_no_can_add_related(self): rel = models.Individual._meta.get_field('parent').rel @@ -631,6 +636,7 @@ class DateTimePickerSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @@ -686,9 +692,11 @@ class DateTimePickerShortcutsSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase self.assertGreater(member.birthdate, now - error_margin) self.assertLess(member.birthdate, now + error_margin) + class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @@ -714,7 +722,7 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp() def assertActiveButtons(self, mode, field_name, choose, remove, - choose_all=None, remove_all=None): + choose_all=None, remove_all=None): choose_link = '#id_%s_add_link' % field_name choose_all_link = '#id_%s_add_all_link' % field_name remove_link = '#id_%s_remove_link' % field_name @@ -928,9 +936,11 @@ class HorizontalVerticalFilterSeleniumFirefoxTests(AdminSeleniumWebDriverTestCas self.assertEqual(list(self.school.alumni.all()), [self.jason, self.peter]) + class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @@ -1025,9 +1035,11 @@ class AdminRawIdWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'), '42,98') + class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' @@ -1072,8 +1084,10 @@ class RelatedFieldWidgetSeleniumFirefoxTests(AdminSeleniumWebDriverTestCase): self.assertEqual(len(profiles), 1) self.assertEqual(profiles[0].user.username, username_value) + class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver' + class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests): webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' diff --git a/tests/aggregation/models.py b/tests/aggregation/models.py index 9710afaf11..691737c17e 100644 --- a/tests/aggregation/models.py +++ b/tests/aggregation/models.py @@ -12,6 +12,7 @@ class Author(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Publisher(models.Model): name = models.CharField(max_length=255) @@ -20,6 +21,7 @@ class Publisher(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Book(models.Model): isbn = models.CharField(max_length=9) @@ -35,6 +37,7 @@ class Book(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Store(models.Model): name = models.CharField(max_length=255) diff --git a/tests/aggregation_regress/models.py b/tests/aggregation_regress/models.py index a2dc060640..275e37c036 100644 --- a/tests/aggregation_regress/models.py +++ b/tests/aggregation_regress/models.py @@ -61,6 +61,7 @@ class Store(models.Model): def __str__(self): return self.name + class Entries(models.Model): EntryID = models.AutoField(primary_key=True, db_column='Entry ID') Entry = models.CharField(unique=True, max_length=50) @@ -69,7 +70,7 @@ class Entries(models.Model): class Clues(models.Model): ID = models.AutoField(primary_key=True) - EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column = 'Entry ID') + EntryID = models.ForeignKey(Entries, verbose_name='Entry', db_column='Entry ID') Clue = models.CharField(max_length=150) @@ -88,13 +89,16 @@ class HardbackBook(Book): def __str__(self): return "%s (hardback): %s" % (self.name, self.weight) + # Models for ticket #21150 class Alfa(models.Model): name = models.CharField(max_length=10, null=True) + class Bravo(models.Model): pass + class Charlie(models.Model): alfa = models.ForeignKey(Alfa, null=True) bravo = models.ForeignKey(Bravo, null=True) diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 3c0cc67ea2..3a79b79411 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -432,6 +432,7 @@ class EscapingChecks(TestCase): # response should be an non-zero integer self.assertTrue(int(response)) + @override_settings(DEBUG=True) class EscapingChecksDebug(EscapingChecks): pass @@ -509,12 +510,12 @@ class BackendTestCase(TestCase): def test_cursor_executemany(self): #4896: Test cursor.executemany - args = [(i, i**2) for i in range(-5, 6)] + args = [(i, i ** 2) for i in range(-5, 6)] self.create_squares_with_executemany(args) self.assertEqual(models.Square.objects.count(), 11) for i in range(-5, 6): square = models.Square.objects.get(root=i) - self.assertEqual(square.square, i**2) + self.assertEqual(square.square, i ** 2) def test_cursor_executemany_with_empty_params_list(self): #4765: executemany with params=[] does nothing @@ -524,11 +525,11 @@ class BackendTestCase(TestCase): def test_cursor_executemany_with_iterator(self): #10320: executemany accepts iterators - args = iter((i, i**2) for i in range(-3, 2)) + args = iter((i, i ** 2) for i in range(-3, 2)) self.create_squares_with_executemany(args) self.assertEqual(models.Square.objects.count(), 5) - args = iter((i, i**2) for i in range(3, 7)) + args = iter((i, i ** 2) for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares_with_executemany(args) @@ -544,20 +545,20 @@ class BackendTestCase(TestCase): @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_cursor_executemany_with_pyformat(self): #10070: Support pyformat style passing of paramters - args = [{'root': i, 'square': i**2} for i in range(-5, 6)] + args = [{'root': i, 'square': i ** 2} for i in range(-5, 6)] self.create_squares(args, 'pyformat', multiple=True) self.assertEqual(models.Square.objects.count(), 11) for i in range(-5, 6): square = models.Square.objects.get(root=i) - self.assertEqual(square.square, i**2) + self.assertEqual(square.square, i ** 2) @skipUnlessDBFeature('supports_paramstyle_pyformat') def test_cursor_executemany_with_pyformat_iterator(self): - args = iter({'root': i, 'square': i**2} for i in range(-3, 2)) + args = iter({'root': i, 'square': i ** 2} for i in range(-3, 2)) self.create_squares(args, 'pyformat', multiple=True) self.assertEqual(models.Square.objects.count(), 5) - args = iter({'root': i, 'square': i**2} for i in range(3, 7)) + args = iter({'root': i, 'square': i ** 2} for i in range(3, 7)) with override_settings(DEBUG=True): # same test for DebugCursorWrapper self.create_squares(args, 'pyformat', multiple=True) @@ -987,6 +988,7 @@ class BackendUtilTests(TestCase): equal('0.1234567890', 12, 0, '0') + @unittest.skipUnless( connection.vendor == 'postgresql', "This test applies only to PostgreSQL") diff --git a/tests/basic/models.py b/tests/basic/models.py index 38cb813d42..5e67b0dca9 100644 --- a/tests/basic/models.py +++ b/tests/basic/models.py @@ -19,11 +19,13 @@ class Article(models.Model): def __str__(self): return self.headline + class ArticleSelectOnSave(Article): class Meta: proxy = True select_on_save = True + @python_2_unicode_compatible class SelfRef(models.Model): selfref = models.ForeignKey('self', null=True, blank=True, diff --git a/tests/basic/tests.py b/tests/basic/tests.py index e4559dc7d7..976fb1124d 100644 --- a/tests/basic/tests.py +++ b/tests/basic/tests.py @@ -87,7 +87,8 @@ class ModelTest(TestCase): # Django raises an Article.DoesNotExist exception for get() if the # parameters don't match any object. - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, ObjectDoesNotExist, "Article matching query does not exist.", Article.objects.get, @@ -102,7 +103,8 @@ class ModelTest(TestCase): pub_date__month=8, ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, ObjectDoesNotExist, "Article matching query does not exist.", Article.objects.get, @@ -135,21 +137,24 @@ class ModelTest(TestCase): # Django raises an Article.MultipleObjectsReturned exception if the # lookup matches more than one object - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, MultipleObjectsReturned, "get\(\) returned more than one Article -- it returned 2!", Article.objects.get, headline__startswith='Area', ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, MultipleObjectsReturned, "get\(\) returned more than one Article -- it returned 2!", Article.objects.get, pub_date__year=2005, ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, MultipleObjectsReturned, "get\(\) returned more than one Article -- it returned 2!", Article.objects.get, @@ -165,14 +170,16 @@ class ModelTest(TestCase): Article(headline='Area %s' % i, pub_date=datetime(2005, 7, 28)) for i in range(MAX_GET_RESULTS) ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, MultipleObjectsReturned, "get\(\) returned more than one Article -- it returned %d!" % MAX_GET_RESULTS, Article.objects.get, headline__startswith='Area', ) Article.objects.create(headline='Area %s' % MAX_GET_RESULTS, pub_date=datetime(2005, 7, 28)) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, MultipleObjectsReturned, "get\(\) returned more than one Article -- it returned more than %d!" % MAX_GET_RESULTS, Article.objects.get, @@ -219,7 +226,8 @@ class ModelTest(TestCase): self.assertEqual(a4.headline, 'Fourth article') # Don't use invalid keyword arguments. - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, TypeError, "'foo' is an invalid keyword argument for this function", Article, @@ -315,7 +323,8 @@ class ModelTest(TestCase): Article.objects.dates, ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, FieldDoesNotExist, "Article has no field named 'invalid_field'", Article.objects.dates, @@ -323,7 +332,8 @@ class ModelTest(TestCase): "year", ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, AssertionError, "'kind' must be one of 'year', 'month' or 'day'.", Article.objects.dates, @@ -331,7 +341,8 @@ class ModelTest(TestCase): "bad_kind", ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, AssertionError, "'order' must be either 'ASC' or 'DESC'.", Article.objects.dates, @@ -419,14 +430,16 @@ class ModelTest(TestCase): ""]) # Also, once you have sliced you can't filter, re-order or combine - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, AssertionError, "Cannot filter a query once a slice has been taken.", Article.objects.all()[0:5].filter, id=a.id, ) - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, AssertionError, "Cannot reorder a query once a slice has been taken.", Article.objects.all()[0:5].order_by, @@ -461,7 +474,8 @@ class ModelTest(TestCase): # An Article instance doesn't have access to the "objects" attribute. # That's only available on the class. - six.assertRaisesRegex(self, + six.assertRaisesRegex( + self, AttributeError, "Manager isn't accessible via Article instances", getattr, @@ -605,8 +619,8 @@ class ModelTest(TestCase): ) dicts = Article.objects.filter( - pub_date__year=2008).extra(select={'dashed-value': '1'} - ).values('headline', 'dashed-value') + pub_date__year=2008).extra( + select={'dashed-value': '1'}).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')]]) @@ -723,6 +737,7 @@ class ModelTest(TestCase): # hash) hash(Article()) + class ConcurrentSaveTests(TransactionTestCase): available_apps = ['basic'] @@ -808,6 +823,7 @@ class ManagerTest(TestCase): sorted(self.QUERYSET_PROXY_METHODS), ) + class SelectOnSaveTests(TestCase): def test_select_on_save(self): a1 = Article.objects.create(pub_date=datetime.now()) diff --git a/tests/bug639/models.py b/tests/bug639/models.py index fa8e7d2c07..3b6a007f6b 100644 --- a/tests/bug639/models.py +++ b/tests/bug639/models.py @@ -8,6 +8,7 @@ from django.forms import ModelForm temp_storage_dir = tempfile.mkdtemp() temp_storage = FileSystemStorage(temp_storage_dir) + class Photo(models.Model): title = models.CharField(max_length=30) image = models.FileField(storage=temp_storage, upload_to='tests') @@ -22,6 +23,7 @@ class Photo(models.Model): super(Photo, self).save(force_insert, force_update) self._savecount += 1 + class PhotoForm(ModelForm): class Meta: model = Photo diff --git a/tests/bulk_create/models.py b/tests/bulk_create/models.py index bc685bbbe4..fcc4b4177e 100644 --- a/tests/bulk_create/models.py +++ b/tests/bulk_create/models.py @@ -5,21 +5,26 @@ class Country(models.Model): name = models.CharField(max_length=255) iso_two_letter = models.CharField(max_length=2) + class Place(models.Model): name = models.CharField(max_length=100) class Meta: abstract = True + class Restaurant(Place): pass + class Pizzeria(Restaurant): pass + class State(models.Model): two_letter_code = models.CharField(max_length=2, primary_key=True) + class TwoFields(models.Model): f1 = models.IntegerField(unique=True) f2 = models.IntegerField(unique=True) diff --git a/tests/cache/closeable_cache.py b/tests/cache/closeable_cache.py index 83073850b7..1ac868dde9 100644 --- a/tests/cache/closeable_cache.py +++ b/tests/cache/closeable_cache.py @@ -7,5 +7,6 @@ class CloseHookMixin(object): def close(self, **kwargs): self.closed = True + class CacheClass(CloseHookMixin, LocMemCache): pass diff --git a/tests/cache/liberal_backend.py b/tests/cache/liberal_backend.py index 3e3ce3beeb..339066b0ff 100644 --- a/tests/cache/liberal_backend.py +++ b/tests/cache/liberal_backend.py @@ -5,5 +5,6 @@ class LiberalKeyValidationMixin(object): def validate_key(self, key): pass + class CacheClass(LiberalKeyValidationMixin, LocMemCache): pass diff --git a/tests/cache/models.py b/tests/cache/models.py index 2cd648b780..4fccbb664b 100644 --- a/tests/cache/models.py +++ b/tests/cache/models.py @@ -7,6 +7,7 @@ def expensive_calculation(): expensive_calculation.num_runs += 1 return timezone.now() + class Poll(models.Model): question = models.CharField(max_length=200) answer = models.CharField(max_length=200) diff --git a/tests/cache/tests.py b/tests/cache/tests.py index a79d4d9fac..a93ed4418a 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -40,10 +40,12 @@ from django.views.decorators.cache import cache_page from .models import Poll, expensive_calculation + # functions/classes for complex data type tests def f(): return 42 + class C: def m(n): return 24 @@ -823,6 +825,7 @@ class BaseCacheTests(object): self.assertEqual(get_cache_data.content, content.encode('utf-8')) self.assertEqual(get_cache_data.cookies, response.cookies) + def custom_key_func(key, key_prefix, version): "A customized cache key function" return 'CUSTOM-' + '-'.join([key_prefix, str(version), key]) @@ -1004,6 +1007,7 @@ class LocMemCacheTests(unittest.TestCase, BaseCacheTests): self.cache.decr(key) self.assertEqual(expire, self.cache._expire_info[_key]) + # memcached backend isn't guaranteed to be available. # To check the memcached backend, the test settings file will # need to contain at least one cache backend setting that points at @@ -1581,6 +1585,7 @@ class CacheI18nTest(TestCase): get_cache_data = FetchFromCacheMiddleware().process_request(request) self.assertIsNone(get_cache_data) + @override_settings( CACHES={ 'default': { @@ -1816,6 +1821,7 @@ class CacheMiddlewareTest(IgnoreDeprecationWarningsMixin, TestCase): response = other_with_prefix_view(request, '16') self.assertEqual(response.content, b'Hello World 16') + @override_settings( CACHE_MIDDLEWARE_KEY_PREFIX='settingsprefix', CACHE_MIDDLEWARE_SECONDS=1, diff --git a/tests/check/models.py b/tests/check/models.py index 212b01bdd2..ddeed23982 100644 --- a/tests/check/models.py +++ b/tests/check/models.py @@ -1,9 +1,11 @@ from django.db import models + class Book(models.Model): title = models.CharField(max_length=250) is_published = models.BooleanField(default=False) + class BlogPost(models.Model): title = models.CharField(max_length=250) is_published = models.BooleanField(default=False) diff --git a/tests/check/tests.py b/tests/check/tests.py index 19b3840a9a..577dcd610b 100644 --- a/tests/check/tests.py +++ b/tests/check/tests.py @@ -7,6 +7,7 @@ from django.test import TestCase from .models import Book + class StubCheckModule(object): # Has no ``run_checks`` attribute & will trigger a warning. __name__ = 'StubCheckModule' diff --git a/tests/choices/models.py b/tests/choices/models.py index 2fa33a9680..4fcef6f48f 100644 --- a/tests/choices/models.py +++ b/tests/choices/models.py @@ -18,6 +18,7 @@ GENDER_CHOICES = ( ('F', 'Female'), ) + @python_2_unicode_compatible class Person(models.Model): name = models.CharField(max_length=20) diff --git a/tests/commands_sql/tests.py b/tests/commands_sql/tests.py index 1a1a190ec5..3a0b5527f4 100644 --- a/tests/commands_sql/tests.py +++ b/tests/commands_sql/tests.py @@ -58,6 +58,7 @@ class TestRouter(object): def allow_migrate(self, db, model): return False + class SQLCommandsRouterTestCase(TestCase): def setUp(self): self._old_routers = router.routers diff --git a/tests/conditional_processing/tests.py b/tests/conditional_processing/tests.py index 77f1ff54ed..2c832e527c 100644 --- a/tests/conditional_processing/tests.py +++ b/tests/conditional_processing/tests.py @@ -15,6 +15,7 @@ EXPIRED_LAST_MODIFIED_STR = 'Sat, 20 Oct 2007 23:21:47 GMT' ETAG = 'b4246ffc4f62314ca13147c9d4f76974' EXPIRED_ETAG = '7fae4cd4b0f81e7d2914700043aa8ed6' + class ConditionalGet(TestCase): urls = 'conditional_processing.urls' diff --git a/tests/conditional_processing/views.py b/tests/conditional_processing/views.py index 2960e0533d..496e79fd34 100644 --- a/tests/conditional_processing/views.py +++ b/tests/conditional_processing/views.py @@ -8,18 +8,22 @@ def index(request): return HttpResponse(FULL_RESPONSE) index = condition(lambda r: ETAG, lambda r: LAST_MODIFIED)(index) + def last_modified_view1(request): return HttpResponse(FULL_RESPONSE) last_modified_view1 = condition(last_modified_func=lambda r: LAST_MODIFIED)(last_modified_view1) + def last_modified_view2(request): return HttpResponse(FULL_RESPONSE) last_modified_view2 = last_modified(lambda r: LAST_MODIFIED)(last_modified_view2) + def etag_view1(request): return HttpResponse(FULL_RESPONSE) etag_view1 = condition(etag_func=lambda r: ETAG)(etag_view1) + def etag_view2(request): return HttpResponse(FULL_RESPONSE) etag_view2 = etag(lambda r: ETAG)(etag_view2) diff --git a/tests/contenttypes_tests/models.py b/tests/contenttypes_tests/models.py index 5d21ad5b96..b2669367eb 100644 --- a/tests/contenttypes_tests/models.py +++ b/tests/contenttypes_tests/models.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible + @python_2_unicode_compatible class Author(models.Model): name = models.CharField(max_length=100) @@ -13,6 +14,7 @@ class Author(models.Model): def get_absolute_url(self): return '/views/authors/%s/' % self.id + @python_2_unicode_compatible class Article(models.Model): title = models.CharField(max_length=100) diff --git a/tests/contenttypes_tests/tests.py b/tests/contenttypes_tests/tests.py index 63f02697df..29ae6c5336 100644 --- a/tests/contenttypes_tests/tests.py +++ b/tests/contenttypes_tests/tests.py @@ -5,6 +5,7 @@ from django.test import TestCase from .models import Author, Article + class ContentTypesViewsTests(TestCase): fixtures = ['testdata.json'] urls = 'contenttypes_tests.urls' diff --git a/tests/csrf_tests/tests.py b/tests/csrf_tests/tests.py index 57f8359cc7..ac48c17af6 100644 --- a/tests/csrf_tests/tests.py +++ b/tests/csrf_tests/tests.py @@ -19,10 +19,12 @@ def post_form_response(): """, mimetype="text/html") return resp + def post_form_view(request): """A view that returns a POST form (without a token)""" return post_form_response() + # Response/views used for template tag tests def token_view(request): @@ -31,6 +33,7 @@ def token_view(request): template = Template("{% csrf_token %}") return HttpResponse(template.render(context)) + def non_token_view_using_request_processor(request): """ A view that doesn't use the token, but does use the csrf view processor. @@ -39,6 +42,7 @@ def non_token_view_using_request_processor(request): template = Template("") return HttpResponse(template.render(context)) + class TestingHttpRequest(HttpRequest): """ A version of HttpRequest that allows us to change some things @@ -47,6 +51,7 @@ class TestingHttpRequest(HttpRequest): def is_secure(self): return getattr(self, '_is_secure_override', False) + class CsrfViewMiddlewareTest(TestCase): # The csrf token is potentially from an untrusted source, so could have # characters that need dealing with. diff --git a/tests/custom_columns/models.py b/tests/custom_columns/models.py index 2549dde749..df1e743be9 100644 --- a/tests/custom_columns/models.py +++ b/tests/custom_columns/models.py @@ -33,6 +33,7 @@ class Author(models.Model): db_table = 'my_author_table' ordering = ('last_name', 'first_name') + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) diff --git a/tests/custom_columns_regress/models.py b/tests/custom_columns_regress/models.py index e848b8ec23..1c026a44c0 100644 --- a/tests/custom_columns_regress/models.py +++ b/tests/custom_columns_regress/models.py @@ -24,6 +24,7 @@ class Article(models.Model): class Meta: ordering = ('headline',) + @python_2_unicode_compatible class Author(models.Model): Author_ID = models.AutoField(primary_key=True, db_column='Author ID') diff --git a/tests/custom_columns_regress/tests.py b/tests/custom_columns_regress/tests.py index 034de08d45..24297b9fa5 100644 --- a/tests/custom_columns_regress/tests.py +++ b/tests/custom_columns_regress/tests.py @@ -10,6 +10,7 @@ def pks(objects): """ Return pks to be able to compare lists""" return [o.pk for o in objects] + class CustomColumnRegression(TestCase): def setUp(self): diff --git a/tests/custom_managers/models.py b/tests/custom_managers/models.py index 26d848b7c0..c6a99620e9 100644 --- a/tests/custom_managers/models.py +++ b/tests/custom_managers/models.py @@ -17,18 +17,21 @@ from django.utils.encoding import python_2_unicode_compatible # An example of a custom manager called "objects". + class PersonManager(models.Manager): def get_fun_people(self): return self.filter(fun=True) # An example of a custom manager that sets get_queryset(). + class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(is_published=True) # An example of a custom queryset that copies its methods onto the manager. + class CustomQuerySet(models.QuerySet): def filter(self, *args, **kwargs): queryset = super(CustomQuerySet, self).filter(fun=True) @@ -49,6 +52,7 @@ class CustomQuerySet(models.QuerySet): return self.all() _optin_private_method.queryset_only = False + class BaseCustomManager(models.Manager): def __init__(self, arg): super(BaseCustomManager, self).__init__() @@ -64,14 +68,17 @@ class BaseCustomManager(models.Manager): CustomManager = BaseCustomManager.from_queryset(CustomQuerySet) + class FunPeopleManager(models.Manager): def get_queryset(self): return super(FunPeopleManager, self).get_queryset().filter(fun=True) + class BoringPeopleManager(models.Manager): def get_queryset(self): return super(BoringPeopleManager, self).get_queryset().filter(fun=False) + @python_2_unicode_compatible class Person(models.Model): first_name = models.CharField(max_length=30) @@ -93,6 +100,7 @@ class Person(models.Model): def __str__(self): return "%s %s" % (self.first_name, self.last_name) + @python_2_unicode_compatible class Book(models.Model): title = models.CharField(max_length=50) @@ -109,10 +117,12 @@ class Book(models.Model): # An example of providing multiple custom managers. + class FastCarManager(models.Manager): def get_queryset(self): return super(FastCarManager, self).get_queryset().filter(top_speed__gt=150) + @python_2_unicode_compatible class Car(models.Model): name = models.CharField(max_length=10) diff --git a/tests/custom_managers_regress/models.py b/tests/custom_managers_regress/models.py index 95cf6e8ca1..eda711f8d7 100644 --- a/tests/custom_managers_regress/models.py +++ b/tests/custom_managers_regress/models.py @@ -13,6 +13,7 @@ class RestrictedManager(models.Manager): def get_queryset(self): return super(RestrictedManager, self).get_queryset().filter(is_public=True) + @python_2_unicode_compatible class RelatedModel(models.Model): name = models.CharField(max_length=50) @@ -20,6 +21,7 @@ class RelatedModel(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class RestrictedModel(models.Model): name = models.CharField(max_length=50) @@ -32,6 +34,7 @@ class RestrictedModel(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class OneToOneRestrictedModel(models.Model): name = models.CharField(max_length=50) diff --git a/tests/custom_pk/fields.py b/tests/custom_pk/fields.py index 92096a0ff7..2aa3bad963 100644 --- a/tests/custom_pk/fields.py +++ b/tests/custom_pk/fields.py @@ -22,6 +22,7 @@ class MyWrapper(object): return self.value == other.value return self.value == other + class MyAutoField(six.with_metaclass(models.SubfieldBase, models.CharField)): def __init__(self, *args, **kwargs): diff --git a/tests/custom_pk/models.py b/tests/custom_pk/models.py index 5fffb84641..bfa6777b10 100644 --- a/tests/custom_pk/models.py +++ b/tests/custom_pk/models.py @@ -16,7 +16,7 @@ from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Employee(models.Model): - employee_code = models.IntegerField(primary_key=True, db_column = 'code') + employee_code = models.IntegerField(primary_key=True, db_column='code') first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) @@ -26,6 +26,7 @@ class Employee(models.Model): def __str__(self): return "%s %s" % (self.first_name, self.last_name) + @python_2_unicode_compatible class Business(models.Model): name = models.CharField(max_length=20, primary_key=True) @@ -37,6 +38,7 @@ class Business(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Bar(models.Model): id = MyAutoField(primary_key=True, db_index=True) diff --git a/tests/datatypes/models.py b/tests/datatypes/models.py index 8e6027dd0f..cabe5297bd 100644 --- a/tests/datatypes/models.py +++ b/tests/datatypes/models.py @@ -23,6 +23,7 @@ class Donut(models.Model): def __str__(self): return self.name + class RumBaba(models.Model): baked_date = models.DateField(auto_now_add=True) baked_timestamp = models.DateTimeField(auto_now_add=True) diff --git a/tests/dates/models.py b/tests/dates/models.py index 23350755e7..d27c22ff67 100644 --- a/tests/dates/models.py +++ b/tests/dates/models.py @@ -14,6 +14,7 @@ class Article(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class Comment(models.Model): article = models.ForeignKey(Article, related_name="comments") @@ -24,5 +25,6 @@ class Comment(models.Model): def __str__(self): return 'Comment to %s (%s)' % (self.article.title, self.pub_date) + class Category(models.Model): name = models.CharField(max_length=255) diff --git a/tests/datetimes/models.py b/tests/datetimes/models.py index f21376aa1c..cfdd521b53 100644 --- a/tests/datetimes/models.py +++ b/tests/datetimes/models.py @@ -14,6 +14,7 @@ class Article(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class Comment(models.Model): article = models.ForeignKey(Article, related_name="comments") @@ -24,5 +25,6 @@ class Comment(models.Model): def __str__(self): return 'Comment to %s (%s)' % (self.article.title, self.pub_date) + class Category(models.Model): name = models.CharField(max_length=255) diff --git a/tests/db_typecasts/tests.py b/tests/db_typecasts/tests.py index 27b89c0c8c..e391743028 100644 --- a/tests/db_typecasts/tests.py +++ b/tests/db_typecasts/tests.py @@ -48,6 +48,7 @@ TEST_CASES = { ), } + class DBTypeCasts(unittest.TestCase): def test_typeCasts(self): for k, v in six.iteritems(TEST_CASES): diff --git a/tests/defer_regress/tests.py b/tests/defer_regress/tests.py index ffb47a8133..c03388b50e 100644 --- a/tests/defer_regress/tests.py +++ b/tests/defer_regress/tests.py @@ -245,6 +245,7 @@ class DeferRegressionTest(TestCase): new_class.__name__, 'Item_Deferred_this_is_some_very_long_attribute_nac34b1f495507dad6b02e2cb235c875e') + class DeferAnnotateSelectRelatedTest(TestCase): def test_defer_annotate_select_related(self): location = Location.objects.create() diff --git a/tests/delete/models.py b/tests/delete/models.py index 65d4e6f725..408b6b83f8 100644 --- a/tests/delete/models.py +++ b/tests/delete/models.py @@ -109,20 +109,26 @@ class HiddenUser(models.Model): class HiddenUserProfile(models.Model): user = models.ForeignKey(HiddenUser) + class M2MTo(models.Model): pass + class M2MFrom(models.Model): m2m = models.ManyToManyField(M2MTo) + class Parent(models.Model): pass + class Child(Parent): pass + class Base(models.Model): pass + class RelToBase(models.Model): base = models.ForeignKey(Base, on_delete=models.DO_NOTHING) diff --git a/tests/delete/tests.py b/tests/delete/tests.py index 7bef83a670..6ecdb01e65 100644 --- a/tests/delete/tests.py +++ b/tests/delete/tests.py @@ -167,7 +167,7 @@ class DeletionTests(TestCase): def test_bulk(self): from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE s = S.objects.create(r=R.objects.create()) - for i in xrange(2*GET_ITERATOR_CHUNK_SIZE): + for i in xrange(2 * GET_ITERATOR_CHUNK_SIZE): T.objects.create(s=s) # 1 (select related `T` instances) # + 1 (select related `U` instances) @@ -311,6 +311,7 @@ class DeletionTests(TestCase): r.delete() self.assertEqual(HiddenUserProfile.objects.count(), 0) + class FastDeleteTests(TestCase): def test_fast_delete_fk(self): diff --git a/tests/delete_regress/models.py b/tests/delete_regress/models.py index 3632a7dbc1..033689519a 100644 --- a/tests/delete_regress/models.py +++ b/tests/delete_regress/models.py @@ -2,51 +2,64 @@ from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.db import models + class Award(models.Model): name = models.CharField(max_length=25) object_id = models.PositiveIntegerField() content_type = models.ForeignKey(ContentType) content_object = generic.GenericForeignKey() + class AwardNote(models.Model): award = models.ForeignKey(Award) note = models.CharField(max_length=100) + class Person(models.Model): name = models.CharField(max_length=25) awards = generic.GenericRelation(Award) + class Book(models.Model): pagecount = models.IntegerField() + class Toy(models.Model): name = models.CharField(max_length=50) + class Child(models.Model): name = models.CharField(max_length=50) toys = models.ManyToManyField(Toy, through='PlayedWith') + class PlayedWith(models.Model): child = models.ForeignKey(Child) toy = models.ForeignKey(Toy) date = models.DateField(db_column='date_col') + class PlayedWithNote(models.Model): played = models.ForeignKey(PlayedWith) note = models.TextField() + class Contact(models.Model): label = models.CharField(max_length=100) + class Email(Contact): email_address = models.EmailField(max_length=100) + class Researcher(models.Model): contacts = models.ManyToManyField(Contact, related_name="research_contacts") + class Food(models.Model): name = models.CharField(max_length=20, unique=True) + class Eaten(models.Model): food = models.ForeignKey(Food, to_field="name") meal = models.CharField(max_length=20) @@ -54,55 +67,70 @@ class Eaten(models.Model): # Models for #15776 + class Policy(models.Model): policy_number = models.CharField(max_length=10) + class Version(models.Model): policy = models.ForeignKey(Policy) + class Location(models.Model): version = models.ForeignKey(Version, blank=True, null=True) + class Item(models.Model): version = models.ForeignKey(Version) location = models.ForeignKey(Location, blank=True, null=True) # Models for #16128 + class File(models.Model): pass + class Image(File): class Meta: proxy = True + class Photo(Image): class Meta: proxy = True + class FooImage(models.Model): my_image = models.ForeignKey(Image) + class FooFile(models.Model): my_file = models.ForeignKey(File) + class FooPhoto(models.Model): my_photo = models.ForeignKey(Photo) + class FooFileProxy(FooFile): class Meta: proxy = True + class OrgUnit(models.Model): name = models.CharField(max_length=64, unique=True) + class Login(models.Model): description = models.CharField(max_length=32) orgunit = models.ForeignKey(OrgUnit) + class House(models.Model): address = models.CharField(max_length=32) + class OrderedPerson(models.Model): name = models.CharField(max_length=32) lives_in = models.ForeignKey(House) diff --git a/tests/delete_regress/tests.py b/tests/delete_regress/tests.py index ecc754920c..e1cbe7070f 100644 --- a/tests/delete_regress/tests.py +++ b/tests/delete_regress/tests.py @@ -146,7 +146,7 @@ class LargeDeleteTests(TestCase): def test_large_deletes(self): "Regression for #13309 -- if the number of objects > chunk size, deletion still occurs" for x in range(300): - Book.objects.create(pagecount=x+100) + Book.objects.create(pagecount=x + 100) # attach a signal to make sure we will not fast-delete def noop(*args, **kwargs): @@ -268,6 +268,7 @@ class ProxyDeleteTest(TestCase): with self.assertRaises(TypeError): Image.objects.values_list().delete() + class Ticket19102Tests(TestCase): """ Test different queries which alter the SELECT clause of the query. We diff --git a/tests/dispatch/tests/test_dispatcher.py b/tests/dispatch/tests/test_dispatcher.py index 9a8d7146cf..1ab4a69d33 100644 --- a/tests/dispatch/tests/test_dispatcher.py +++ b/tests/dispatch/tests/test_dispatcher.py @@ -23,9 +23,11 @@ else: def garbage_collect(): gc.collect() + def receiver_1_arg(val, **kwargs): return val + class Callable(object): def __call__(self, val, **kwargs): return val @@ -116,10 +118,10 @@ class DispatcherTests(unittest.TestCase): def uid_based_receiver_2(**kwargs): pass - a_signal.connect(uid_based_receiver_1, dispatch_uid = "uid") - a_signal.connect(uid_based_receiver_2, dispatch_uid = "uid") + a_signal.connect(uid_based_receiver_1, dispatch_uid="uid") + a_signal.connect(uid_based_receiver_2, dispatch_uid="uid") self.assertEqual(len(a_signal.receivers), 1) - a_signal.disconnect(dispatch_uid = "uid") + a_signal.disconnect(dispatch_uid="uid") self._testIsClean(a_signal) def testRobust(self): diff --git a/tests/dispatch/tests/test_saferef.py b/tests/dispatch/tests/test_saferef.py index 531e8f43de..6da756362a 100644 --- a/tests/dispatch/tests/test_saferef.py +++ b/tests/dispatch/tests/test_saferef.py @@ -3,17 +3,21 @@ import unittest from django.dispatch.saferef import safeRef from django.utils.six.moves import xrange + class Test1(object): def x(self): pass + def test2(obj): pass + class Test2(object): def __call__(self, obj): pass + class SaferefTests(unittest.TestCase): def setUp(self): ts = [] diff --git a/tests/distinct_on_fields/models.py b/tests/distinct_on_fields/models.py index 7982f435d0..053fd9cc5f 100644 --- a/tests/distinct_on_fields/models.py +++ b/tests/distinct_on_fields/models.py @@ -3,6 +3,7 @@ from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible + @python_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=10) @@ -15,6 +16,7 @@ class Tag(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Celebrity(models.Model): name = models.CharField("Name", max_length=20) @@ -23,9 +25,11 @@ class Celebrity(models.Model): def __str__(self): return self.name + class Fan(models.Model): fan_of = models.ForeignKey(Celebrity) + @python_2_unicode_compatible class Staff(models.Model): id = models.IntegerField(primary_key=True) @@ -37,6 +41,7 @@ class Staff(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class StaffTag(models.Model): staff = models.ForeignKey(Staff) diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py index e14f06f2ed..9dedd98f81 100644 --- a/tests/distinct_on_fields/tests.py +++ b/tests/distinct_on_fields/tests.py @@ -6,6 +6,7 @@ from django.test.utils import str_prefix from .models import Tag, Celebrity, Fan, Staff, StaffTag + @skipUnlessDBFeature('can_distinct_on_fields') class DistinctOnTests(TestCase): def setUp(self): @@ -77,7 +78,7 @@ class DistinctOnTests(TestCase): # Fetch the alphabetically first coworker for each worker ( (Staff.objects.distinct('id').order_by('id', 'coworkers__name'). - values_list('id', 'coworkers__name')), + values_list('id', 'coworkers__name')), [str_prefix("(1, %(_)s'p2')"), str_prefix("(2, %(_)s'p1')"), str_prefix("(3, %(_)s'p1')"), "(4, None)"] ), diff --git a/tests/expressions/models.py b/tests/expressions/models.py index f592a0eb13..e66bb0a135 100644 --- a/tests/expressions/models.py +++ b/tests/expressions/models.py @@ -15,6 +15,7 @@ class Employee(models.Model): def __str__(self): return '%s %s' % (self.firstname, self.lastname) + @python_2_unicode_compatible class Company(models.Model): name = models.CharField(max_length=100) diff --git a/tests/expressions_regress/models.py b/tests/expressions_regress/models.py index bd3e52f54d..c70338933a 100644 --- a/tests/expressions_regress/models.py +++ b/tests/expressions_regress/models.py @@ -14,6 +14,7 @@ class Number(models.Model): def __str__(self): return '%i, %.3f' % (self.integer, self.float) + class Experiment(models.Model): name = models.CharField(max_length=24) assigned = models.DateField() diff --git a/tests/expressions_regress/tests.py b/tests/expressions_regress/tests.py index 0e168e924a..e603c410ac 100644 --- a/tests/expressions_regress/tests.py +++ b/tests/expressions_regress/tests.py @@ -79,12 +79,12 @@ class ExpressionsRegressTests(TestCase): """ n = Number.objects.create(integer=10, float=123.45) self.assertEqual(Number.objects.filter(pk=n.pk) - .update(float=F('integer') + F('float') * 2), - 1) + .update(float=F('integer') + F('float') * 2), 1) self.assertEqual(Number.objects.get(pk=n.pk).integer, 10) self.assertEqual(Number.objects.get(pk=n.pk).float, Approximate(256.900, places=3)) + class ExpressionOperatorTests(TestCase): def setUp(self): self.n = Number.objects.create(integer=42, float=15.5) @@ -220,13 +220,13 @@ class FTimeDeltaTests(TestCase): self.days_long = [] # e0: started same day as assigned, zero duration - end = stime+delta0 + end = stime + delta0 e0 = Experiment.objects.create(name='e0', assigned=sday, start=stime, end=end, completed=end.date()) self.deltas.append(delta0) self.delays.append(e0.start - datetime.datetime.combine(e0.assigned, midnight)) - self.days_long.append(e0.completed-e0.assigned) + self.days_long.append(e0.completed - e0.assigned) # e1: started one day after assigned, tiny duration, data # set so that end time has no fractional seconds, which @@ -237,86 +237,86 @@ class FTimeDeltaTests(TestCase): delay = datetime.timedelta(1) end = stime + delay + delta1 e1 = Experiment.objects.create(name='e1', assigned=sday, - start=stime+delay, end=end, completed=end.date()) + start=stime + delay, end=end, completed=end.date()) self.deltas.append(delta1) self.delays.append(e1.start - datetime.datetime.combine(e1.assigned, midnight)) - self.days_long.append(e1.completed-e1.assigned) + self.days_long.append(e1.completed - e1.assigned) # e2: started three days after assigned, small duration - end = stime+delta2 + end = stime + delta2 e2 = Experiment.objects.create(name='e2', - assigned=sday-datetime.timedelta(3), start=stime, end=end, + assigned=sday - datetime.timedelta(3), start=stime, end=end, completed=end.date()) self.deltas.append(delta2) self.delays.append(e2.start - datetime.datetime.combine(e2.assigned, midnight)) - self.days_long.append(e2.completed-e2.assigned) + self.days_long.append(e2.completed - e2.assigned) # e3: started four days after assigned, medium duration delay = datetime.timedelta(4) end = stime + delay + delta3 e3 = Experiment.objects.create(name='e3', - assigned=sday, start=stime+delay, end=end, completed=end.date()) + assigned=sday, start=stime + delay, end=end, completed=end.date()) self.deltas.append(delta3) self.delays.append(e3.start - datetime.datetime.combine(e3.assigned, midnight)) - self.days_long.append(e3.completed-e3.assigned) + self.days_long.append(e3.completed - e3.assigned) # e4: started 10 days after assignment, long duration end = stime + delta4 e4 = Experiment.objects.create(name='e4', - assigned=sday-datetime.timedelta(10), start=stime, end=end, + assigned=sday - datetime.timedelta(10), start=stime, end=end, completed=end.date()) self.deltas.append(delta4) self.delays.append(e4.start - datetime.datetime.combine(e4.assigned, midnight)) - self.days_long.append(e4.completed-e4.assigned) + self.days_long.append(e4.completed - e4.assigned) self.expnames = [e.name for e in Experiment.objects.all()] def test_delta_add(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in - Experiment.objects.filter(end__lt=F('start')+delta)] + Experiment.objects.filter(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in - Experiment.objects.filter(end__lte=F('start')+delta)] - self.assertEqual(test_set, self.expnames[:i+1]) + Experiment.objects.filter(end__lte=F('start') + delta)] + self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_subtract(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in - Experiment.objects.filter(start__gt=F('end')-delta)] + Experiment.objects.filter(start__gt=F('end') - delta)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in - Experiment.objects.filter(start__gte=F('end')-delta)] - self.assertEqual(test_set, self.expnames[:i+1]) + Experiment.objects.filter(start__gte=F('end') - delta)] + self.assertEqual(test_set, self.expnames[:i + 1]) def test_exclude(self): for i in range(len(self.deltas)): delta = self.deltas[i] test_set = [e.name for e in - Experiment.objects.exclude(end__lt=F('start')+delta)] + Experiment.objects.exclude(end__lt=F('start') + delta)] self.assertEqual(test_set, self.expnames[i:]) test_set = [e.name for e in - Experiment.objects.exclude(end__lte=F('start')+delta)] - self.assertEqual(test_set, self.expnames[i+1:]) + Experiment.objects.exclude(end__lte=F('start') + delta)] + self.assertEqual(test_set, self.expnames[i + 1:]) def test_date_comparison(self): for i in range(len(self.days_long)): days = self.days_long[i] test_set = [e.name for e in - Experiment.objects.filter(completed__lt=F('assigned')+days)] + Experiment.objects.filter(completed__lt=F('assigned') + days)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in - Experiment.objects.filter(completed__lte=F('assigned')+days)] - self.assertEqual(test_set, self.expnames[:i+1]) + Experiment.objects.filter(completed__lte=F('assigned') + days)] + self.assertEqual(test_set, self.expnames[:i + 1]) @skipUnlessDBFeature("supports_mixed_date_datetime_comparisons") def test_mixed_comparisons1(self): @@ -325,35 +325,35 @@ class FTimeDeltaTests(TestCase): if not connection.features.supports_microsecond_precision: delay = datetime.timedelta(delay.days, delay.seconds) test_set = [e.name for e in - Experiment.objects.filter(assigned__gt=F('start')-delay)] + Experiment.objects.filter(assigned__gt=F('start') - delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in - Experiment.objects.filter(assigned__gte=F('start')-delay)] - self.assertEqual(test_set, self.expnames[:i+1]) + Experiment.objects.filter(assigned__gte=F('start') - delay)] + self.assertEqual(test_set, self.expnames[:i + 1]) def test_mixed_comparisons2(self): delays = [datetime.timedelta(delay.days) for delay in self.delays] for i in range(len(delays)): delay = delays[i] test_set = [e.name for e in - Experiment.objects.filter(start__lt=F('assigned')+delay)] + Experiment.objects.filter(start__lt=F('assigned') + delay)] self.assertEqual(test_set, self.expnames[:i]) test_set = [e.name for e in Experiment.objects.filter(start__lte=F('assigned') + delay + datetime.timedelta(1))] - self.assertEqual(test_set, self.expnames[:i+1]) + self.assertEqual(test_set, self.expnames[:i + 1]) def test_delta_update(self): for i in range(len(self.deltas)): delta = self.deltas[i] exps = Experiment.objects.all() expected_durations = [e.duration() for e in exps] - expected_starts = [e.start+delta for e in exps] - expected_ends = [e.end+delta for e in exps] + expected_starts = [e.start + delta for e in exps] + expected_ends = [e.end + delta for e in exps] - Experiment.objects.update(start=F('start')+delta, end=F('end')+delta) + Experiment.objects.update(start=F('start') + delta, end=F('end') + delta) exps = Experiment.objects.all() new_starts = [e.start for e in exps] new_ends = [e.end for e in exps] @@ -365,7 +365,7 @@ class FTimeDeltaTests(TestCase): def test_delta_invalid_op_mult(self): raised = False try: - repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0])) + repr(Experiment.objects.filter(end__lt=F('start') * self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.") @@ -373,7 +373,7 @@ class FTimeDeltaTests(TestCase): def test_delta_invalid_op_div(self): raised = False try: - repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0])) + repr(Experiment.objects.filter(end__lt=F('start') / self.deltas[0])) except TypeError: raised = True self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.") diff --git a/tests/extra_regress/models.py b/tests/extra_regress/models.py index 5523a06a8a..432aa02963 100644 --- a/tests/extra_regress/models.py +++ b/tests/extra_regress/models.py @@ -30,10 +30,12 @@ class RevisionableModel(models.Model): new_revision.pk = None return new_revision + class Order(models.Model): created_by = models.ForeignKey(User) text = models.TextField() + @python_2_unicode_compatible class TestObject(models.Model): first = models.CharField(max_length=20) diff --git a/tests/field_subclassing/fields.py b/tests/field_subclassing/fields.py index a3867e3671..e9c7a982e8 100644 --- a/tests/field_subclassing/fields.py +++ b/tests/field_subclassing/fields.py @@ -20,6 +20,7 @@ class Small(object): def __str__(self): return '%s%s' % (force_text(self.first), force_text(self.second)) + class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)): """ Turns the "Small" class into a Django field. Because of the similarities @@ -51,6 +52,7 @@ class SmallField(six.with_metaclass(models.SubfieldBase, models.Field)): return [] raise TypeError('Invalid lookup type: %r' % lookup_type) + class SmallerField(SmallField): pass diff --git a/tests/field_subclassing/models.py b/tests/field_subclassing/models.py index 67a95b02f2..c2f7e4f66b 100644 --- a/tests/field_subclassing/models.py +++ b/tests/field_subclassing/models.py @@ -17,8 +17,10 @@ class MyModel(models.Model): def __str__(self): return force_text(self.name) + class OtherModel(models.Model): data = SmallerField() + class DataModel(models.Model): data = JSONField() diff --git a/tests/file_storage/models.py b/tests/file_storage/models.py index eea3ddaf09..738a3a1772 100644 --- a/tests/file_storage/models.py +++ b/tests/file_storage/models.py @@ -15,6 +15,7 @@ from django.core.files.storage import FileSystemStorage temp_storage_location = tempfile.mkdtemp() temp_storage = FileSystemStorage(location=temp_storage_location) + class Storage(models.Model): def custom_upload_to(self, filename): return 'foo' diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index 1f676d04b1..20eaf4c89c 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -69,6 +69,7 @@ class GetStorageClassTests(SimpleTestCase): get_storage_class( 'django.core.files.non_existing_storage.NonExistingStorage') + class FileStorageTests(unittest.TestCase): storage_class = FileSystemStorage @@ -379,6 +380,7 @@ class CustomStorage(FileSystemStorage): return name + class CustomStorageTests(FileStorageTests): storage_class = CustomStorage @@ -531,6 +533,7 @@ class SlowFile(ContentFile): time.sleep(1) return super(ContentFile, self).chunks() + class FileSaveRaceConditionTest(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() @@ -552,6 +555,7 @@ class FileSaveRaceConditionTest(unittest.TestCase): self.storage.delete('conflict') self.storage.delete('conflict_1') + @unittest.skipIf(sys.platform.startswith('win'), "Windows only partially supports umasks and chmod.") class FileStoragePermissions(unittest.TestCase): def setUp(self): @@ -591,6 +595,7 @@ class FileStoragePermissions(unittest.TestCase): dir_mode = os.stat(os.path.dirname(self.storage.path(name)))[0] & 0o777 self.assertEqual(dir_mode, 0o777 & ~self.umask) + class FileStoragePathParsing(unittest.TestCase): def setUp(self): self.storage_dir = tempfile.mkdtemp() diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 72f9d7a77c..7aa6797630 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -397,6 +397,7 @@ class FileUploadTests(TestCase): # shouldn't differ. self.assertEqual(os.path.basename(obj.testfile.path), 'MiXeD_cAsE.txt') + @override_settings(MEDIA_ROOT=MEDIA_ROOT) class DirectoryCreationTests(TestCase): """ @@ -436,7 +437,7 @@ class DirectoryCreationTests(TestCase): # The test needs to be done on a specific string as IOError # is raised even without the patch (just not early enough) self.assertEqual(exc_info.exception.args[0], - "%s exists and is not a directory." % UPLOAD_TO) + "%s exists and is not a directory." % UPLOAD_TO) class MultiParserTests(unittest.TestCase): diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py index 2d4e52e4d5..b69cc751cb 100644 --- a/tests/file_uploads/uploadhandler.py +++ b/tests/file_uploads/uploadhandler.py @@ -11,7 +11,7 @@ class QuotaUploadHandler(FileUploadHandler): (5MB) is uploaded. """ - QUOTA = 5 * 2**20 # 5 MB + QUOTA = 5 * 2 ** 20 # 5 MB def __init__(self, request=None): super(QuotaUploadHandler, self).__init__(request) @@ -26,9 +26,11 @@ class QuotaUploadHandler(FileUploadHandler): def file_complete(self, file_size): return None + class CustomUploadError(Exception): pass + class ErroringUploadHandler(FileUploadHandler): """A handler that raises an exception.""" def receive_data_chunk(self, raw_data, start): diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py index 1940987815..a29391af6e 100644 --- a/tests/file_uploads/views.py +++ b/tests/file_uploads/views.py @@ -30,6 +30,7 @@ def file_upload_view(request): else: return HttpResponseServerError() + def file_upload_view_verify(request): """ Use the sha digest hash to verify the uploaded contents. @@ -57,6 +58,7 @@ def file_upload_view_verify(request): return HttpResponse('') + def file_upload_unicode_name(request): # Check to see if unicode name came through properly. @@ -85,6 +87,7 @@ def file_upload_unicode_name(request): else: return HttpResponse('') + def file_upload_echo(request): """ Simple view to echo back info about uploaded files for tests. @@ -92,6 +95,7 @@ def file_upload_echo(request): r = dict((k, f.name) for k, f in request.FILES.items()) return HttpResponse(json.dumps(r)) + def file_upload_echo_content(request): """ Simple view to echo back the content of uploaded files for tests. @@ -99,6 +103,7 @@ def file_upload_echo_content(request): r = dict((k, f.read().decode('utf-8')) for k, f in request.FILES.items()) return HttpResponse(json.dumps(r)) + def file_upload_quota(request): """ Dynamically add in an upload handler. @@ -106,6 +111,7 @@ def file_upload_quota(request): request.upload_handlers.insert(0, QuotaUploadHandler()) return file_upload_echo(request) + def file_upload_quota_broken(request): """ You can't change handlers after reading FILES; this view shouldn't work. @@ -114,6 +120,7 @@ def file_upload_quota_broken(request): request.upload_handlers.insert(0, QuotaUploadHandler()) return response + def file_upload_getlist_count(request): """ Check the .getlist() function to ensure we receive the correct number of files. @@ -124,10 +131,12 @@ def file_upload_getlist_count(request): file_counts[key] = len(request.FILES.getlist(key)) return HttpResponse(json.dumps(file_counts)) + def file_upload_errors(request): request.upload_handlers.insert(0, ErroringUploadHandler()) return file_upload_echo(request) + def file_upload_filename_case_view(request): """ Check adding the file to the database will preserve the filename case. @@ -137,6 +146,7 @@ def file_upload_filename_case_view(request): obj.testfile.save(file.name, file) return HttpResponse('%d' % obj.pk) + def file_upload_content_type_extra(request): """ Simple view to echo back extra content-type parameters. diff --git a/tests/fixtures/models.py b/tests/fixtures/models.py index 56bb601c27..08cb02ce72 100644 --- a/tests/fixtures/models.py +++ b/tests/fixtures/models.py @@ -26,6 +26,7 @@ class Category(models.Model): class Meta: ordering = ('title',) + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100, default='Default headline') @@ -37,6 +38,7 @@ class Article(models.Model): class Meta: ordering = ('-pub_date', 'headline') + @python_2_unicode_compatible class Blog(models.Model): name = models.CharField(max_length=100) @@ -60,10 +62,12 @@ class Tag(models.Model): return '<%s: %s> tagged "%s"' % (self.tagged.__class__.__name__, self.tagged, self.name) + class PersonManager(models.Manager): def get_by_natural_key(self, name): return self.get(name=name) + @python_2_unicode_compatible class Person(models.Model): objects = PersonManager() @@ -78,14 +82,17 @@ class Person(models.Model): def natural_key(self): return (self.name,) + class SpyManager(PersonManager): def get_queryset(self): return super(SpyManager, self).get_queryset().filter(cover_blown=False) + class Spy(Person): objects = SpyManager() cover_blown = models.BooleanField(default=False) + @python_2_unicode_compatible class Visa(models.Model): person = models.ForeignKey(Person) @@ -95,6 +102,7 @@ class Visa(models.Model): return '%s %s' % (self.person.name, ', '.join(p.name for p in self.permissions.all())) + @python_2_unicode_compatible class Book(models.Model): name = models.CharField(max_length=100) diff --git a/tests/fixtures_model_package/models/__init__.py b/tests/fixtures_model_package/models/__init__.py index deeba48aa9..c48cfd451d 100644 --- a/tests/fixtures_model_package/models/__init__.py +++ b/tests/fixtures_model_package/models/__init__.py @@ -14,6 +14,7 @@ class Article(models.Model): app_label = 'fixtures_model_package' ordering = ('-pub_date', 'headline') + class Book(models.Model): name = models.CharField(max_length=100) diff --git a/tests/fixtures_regress/models.py b/tests/fixtures_regress/models.py index 4b33cef09b..95f9488ab7 100644 --- a/tests/fixtures_regress/models.py +++ b/tests/fixtures_regress/models.py @@ -27,6 +27,7 @@ class Plant(models.Model): # For testing when upper case letter in app name; regression for #4057 db_table = "Fixtures_regress_plant" + @python_2_unicode_compatible class Stuff(models.Model): name = models.CharField(max_length=20, null=True) diff --git a/tests/force_insert_update/models.py b/tests/force_insert_update/models.py index 56d6624e0d..7067613ccd 100644 --- a/tests/force_insert_update/models.py +++ b/tests/force_insert_update/models.py @@ -9,16 +9,20 @@ class Counter(models.Model): name = models.CharField(max_length = 10) value = models.IntegerField() + class InheritedCounter(Counter): tag = models.CharField(max_length=10) + class ProxyCounter(Counter): class Meta: proxy = True + class SubCounter(Counter): pass + class WithCustomPK(models.Model): name = models.IntegerField(primary_key=True) value = models.IntegerField() diff --git a/tests/foreign_object/models.py b/tests/foreign_object/models.py index d8c3bc10d4..7673d27af6 100644 --- a/tests/foreign_object/models.py +++ b/tests/foreign_object/models.py @@ -5,6 +5,7 @@ from django.db.models.fields.related import ReverseSingleRelatedObjectDescriptor from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import get_language + @python_2_unicode_compatible class Country(models.Model): # Table Column Fields @@ -13,6 +14,7 @@ class Country(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Person(models.Model): # Table Column Fields @@ -30,6 +32,7 @@ class Person(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Group(models.Model): # Table Column Fields @@ -96,6 +99,7 @@ class Friendship(models.Model): to_fields=['person_country_id', 'id'], related_name='to_friend') + class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor): """ The set of articletranslation should not set any local fields. @@ -107,6 +111,7 @@ class ArticleTranslationDescriptor(ReverseSingleRelatedObjectDescriptor): if value is not None and not self.field.rel.multiple: setattr(value, self.field.related.get_cache_name(), instance) + class ColConstraint(object): # Antyhing with as_sql() method works in get_extra_restriction(). def __init__(self, alias, col, value): @@ -115,6 +120,7 @@ class ColConstraint(object): def as_sql(self, qn, connection): return '%s.%s = %%s' % (qn(self.alias), qn(self.col)), [self.value] + class ActiveTranslationField(models.ForeignObject): """ This field will allow querying and fetching the currently active translation @@ -132,6 +138,7 @@ class ActiveTranslationField(models.ForeignObject): super(ActiveTranslationField, self).contribute_to_class(cls, name) setattr(cls, self.name, ArticleTranslationDescriptor(self)) + @python_2_unicode_compatible class Article(models.Model): active_translation = ActiveTranslationField( @@ -148,9 +155,11 @@ class Article(models.Model): except ArticleTranslation.DoesNotExist: return '[No translation found]' + class NewsArticle(Article): pass + class ArticleTranslation(models.Model): article = models.ForeignKey(Article) lang = models.CharField(max_length='2') @@ -162,10 +171,12 @@ class ArticleTranslation(models.Model): unique_together = ('article', 'lang') ordering = ('active_translation__title',) + class ArticleTag(models.Model): article = models.ForeignKey(Article, related_name="tags", related_query_name="tag") name = models.CharField(max_length=255) + class ArticleIdea(models.Model): articles = models.ManyToManyField(Article, related_name="ideas", related_query_name="idea_things") diff --git a/tests/foreign_object/tests.py b/tests/foreign_object/tests.py index 77582162a8..66f57b6f3c 100644 --- a/tests/foreign_object/tests.py +++ b/tests/foreign_object/tests.py @@ -12,6 +12,7 @@ from django import forms # Note that these tests are testing internal implementation details. # ForeignObject is not part of public API. + class MultiColumnFKTests(TestCase): def setUp(self): # Creating countries @@ -379,6 +380,7 @@ class MultiColumnFKTests(TestCase): 'active_translation')[0].active_translation.title, "foo") + class FormsTests(TestCase): # ForeignObjects should not have any form fields, currently the user needs # to manually deal with the foreignobject relation. diff --git a/tests/forms_tests/models.py b/tests/forms_tests/models.py index 33898ffbb8..8ade923a91 100644 --- a/tests/forms_tests/models.py +++ b/tests/forms_tests/models.py @@ -19,6 +19,8 @@ class BoundaryModel(models.Model): callable_default_value = 0 + + def callable_default(): global callable_default_value callable_default_value = callable_default_value + 1 @@ -27,7 +29,7 @@ def callable_default(): class Defaults(models.Model): name = models.CharField(max_length=255, default='class default value') - def_date = models.DateField(default = datetime.date(1980, 1, 1)) + def_date = models.DateField(default=datetime.date(1980, 1, 1)) value = models.IntegerField(default=42) callable_default = models.IntegerField(default=callable_default) @@ -86,6 +88,7 @@ class ChoiceFieldModel(models.Model): multi_choice_int = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='multi_choice_int', default=lambda: [1]) + class OptionalMultiChoiceModel(models.Model): multi_choice = models.ManyToManyField(ChoiceOptionModel, blank=False, related_name='not_relevant', default=lambda: ChoiceOptionModel.objects.filter(name='default')) diff --git a/tests/forms_tests/tests/test_error_messages.py b/tests/forms_tests/tests/test_error_messages.py index 2d532c7cf9..86f26df3bc 100644 --- a/tests/forms_tests/tests/test_error_messages.py +++ b/tests/forms_tests/tests/test_error_messages.py @@ -24,6 +24,7 @@ class AssertFormErrorsMixin(object): except ValidationError as e: self.assertEqual(e.messages, expected) + class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin): def test_charfield(self): e = { diff --git a/tests/forms_tests/tests/test_extra.py b/tests/forms_tests/tests/test_extra.py index 183b5dabdf..4585a4e6ef 100644 --- a/tests/forms_tests/tests/test_extra.py +++ b/tests/forms_tests/tests/test_extra.py @@ -25,12 +25,15 @@ from .test_error_messages import AssertFormErrorsMixin class GetDate(Form): mydate = DateField(widget=SelectDateWidget) + class GetNotRequiredDate(Form): mydate = DateField(widget=SelectDateWidget, required=False) + class GetDateShowHiddenInitial(Form): mydate = DateField(widget=SelectDateWidget, show_hidden_initial=True) + class FormsExtraTestCase(TestCase, AssertFormErrorsMixin): ############### # Extra stuff # diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index cf721b5510..52dfdf4044 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -57,7 +57,7 @@ SplitDateTimeFormSet = formset_factory(SplitDateTimeForm) class FormsFormsetTestCase(TestCase): def make_choiceformset(self, formset_data=None, formset_class=ChoiceFormSet, - total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): + total_forms=None, initial_forms=0, max_num_forms=0, min_num_forms=0, **kwargs): """ Make a ChoiceFormset from the given formset_data. The data should be given as a list of (choice, votes) tuples. @@ -1097,12 +1097,14 @@ data = { 'choices-0-votes': '100', } + class Choice(Form): choice = CharField() votes = IntegerField() ChoiceFormSet = formset_factory(Choice) + class FormsetAsFooTests(TestCase): def test_as_table(self): formset = ChoiceFormSet(data, auto_id=False, prefix='choices') @@ -1130,6 +1132,7 @@ class ArticleForm(Form): ArticleFormSet = formset_factory(ArticleForm) + class TestIsBoundBehavior(TestCase): def test_no_data_raises_validation_error(self): with self.assertRaises(ValidationError): @@ -1184,6 +1187,7 @@ class TestIsBoundBehavior(TestCase): # The empty forms should be equal. self.assertHTMLEqual(empty_forms[0].as_p(), empty_forms[1].as_p()) + class TestEmptyFormSet(TestCase): def test_empty_formset_is_valid(self): """Test that an empty formset still calls clean()""" diff --git a/tests/forms_tests/tests/test_input_formats.py b/tests/forms_tests/tests/test_input_formats.py index 25b491a499..b9c29c7609 100644 --- a/tests/forms_tests/tests/test_input_formats.py +++ b/tests/forms_tests/tests/test_input_formats.py @@ -490,6 +490,7 @@ class CustomDateInputFormatsTests(SimpleTestCase): text = f.widget._format_value(result) self.assertEqual(text, "21.12.2010") + class SimpleDateFormatTests(SimpleTestCase): def test_dateField(self): "DateFields can parse dates in the default format" @@ -776,6 +777,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase): text = f.widget._format_value(result) self.assertEqual(text, "01:30:00 PM 21/12/2010") + class SimpleDateTimeFormatTests(SimpleTestCase): def test_dateTimeField(self): "DateTimeFields can parse dates in the default format" diff --git a/tests/forms_tests/tests/test_widgets.py b/tests/forms_tests/tests/test_widgets.py index c601a3ad58..21134d1a24 100644 --- a/tests/forms_tests/tests/test_widgets.py +++ b/tests/forms_tests/tests/test_widgets.py @@ -286,7 +286,7 @@ class FormsWidgetTestCase(TestCase): things = ({'id': 1, 'name': 'And Boom'}, {'id': 2, 'name': 'One More Thing!'}) class SomeForm(Form): - somechoice = ChoiceField(choices=chain((('', '-'*9),), [(thing['id'], thing['name']) for thing in things])) + somechoice = ChoiceField(choices=chain((('', '-' * 9),), [(thing['id'], thing['name']) for thing in things])) f = SomeForm() self.assertHTMLEqual(f.as_table(), '') self.assertHTMLEqual(f.as_table(), '') @@ -1003,6 +1003,7 @@ class NullBooleanSelectLazyForm(Form): """Form to test for lazy evaluation. Refs #17190""" bool = BooleanField(widget=NullBooleanSelect()) + @override_settings(USE_L10N=True) class FormsI18NWidgetsTestCase(TestCase): def setUp(self): @@ -1136,6 +1137,7 @@ class FakeFieldFile(object): def __str__(self): return self.url + class ClearableFileInputTests(TestCase): def test_clear_input_renders(self): """ diff --git a/tests/forms_tests/tests/tests.py b/tests/forms_tests/tests/tests.py index 8212d4ee5c..622b6386e9 100644 --- a/tests/forms_tests/tests/tests.py +++ b/tests/forms_tests/tests/tests.py @@ -217,6 +217,7 @@ class FormsModelTestCase(TestCase): self.assertEqual(obj.value, 99) self.assertEqual(obj.def_date, datetime.date(1999, 3, 2)) + class RelatedModelFormTests(TestCase): def test_invalid_loading_order(self): """ diff --git a/tests/generic_inline_admin/admin.py b/tests/generic_inline_admin/admin.py index 1917024fa5..c701e4a9eb 100644 --- a/tests/generic_inline_admin/admin.py +++ b/tests/generic_inline_admin/admin.py @@ -7,6 +7,7 @@ from .models import (Media, PhoneNumber, Episode, EpisodeExtra, Contact, site = admin.AdminSite(name="admin") + class MediaInline(generic.GenericTabularInline): model = Media diff --git a/tests/generic_inline_admin/models.py b/tests/generic_inline_admin/models.py index cc7de62454..af3a474cdf 100644 --- a/tests/generic_inline_admin/models.py +++ b/tests/generic_inline_admin/models.py @@ -34,6 +34,7 @@ class Media(models.Model): # Generic inline with extra = 0 # + class EpisodeExtra(Episode): pass @@ -67,6 +68,7 @@ class Contact(models.Model): name = models.CharField(max_length=50) phone_numbers = generic.GenericRelation(PhoneNumber) + # # Generic inline with can_delete=False # diff --git a/tests/generic_inline_admin/tests.py b/tests/generic_inline_admin/tests.py index 23f17f7b22..09a802a1bc 100644 --- a/tests/generic_inline_admin/tests.py +++ b/tests/generic_inline_admin/tests.py @@ -129,6 +129,7 @@ class GenericAdminViewTest(TestCase): formset = inline_formset(instance=e) self.assertTrue(formset.get_queryset().ordered) + @override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',)) class GenericInlineAdminParametersTest(TestCase): urls = "generic_inline_admin.urls" @@ -210,6 +211,7 @@ class GenericInlineAdminWithUniqueTogetherTest(TestCase): response = self.client.post('/generic_inline_admin/admin/generic_inline_admin/contact/add/', post_data) self.assertEqual(response.status_code, 302) # redirect somewhere + class NoInlineDeletionTest(TestCase): urls = "generic_inline_admin.urls" @@ -224,6 +226,7 @@ class NoInlineDeletionTest(TestCase): class MockRequest(object): pass + class MockSuperUser(object): def has_perm(self, perm): return True diff --git a/tests/generic_relations/tests.py b/tests/generic_relations/tests.py index 60821903d9..8cd319bf03 100644 --- a/tests/generic_relations/tests.py +++ b/tests/generic_relations/tests.py @@ -290,12 +290,14 @@ class GenericRelationsTests(TestCase): class CustomWidget(forms.TextInput): pass + class TaggedItemForm(forms.ModelForm): class Meta: model = TaggedItem fields = '__all__' widgets = {'tag': CustomWidget} + class GenericInlineFormsetTest(TestCase): def test_generic_inlineformset_factory(self): """ diff --git a/tests/generic_relations_regress/models.py b/tests/generic_relations_regress/models.py index d716f09058..300ed9d54a 100644 --- a/tests/generic_relations_regress/models.py +++ b/tests/generic_relations_regress/models.py @@ -8,6 +8,7 @@ __all__ = ('Link', 'Place', 'Restaurant', 'Person', 'Address', 'CharLink', 'TextLink', 'OddRelation1', 'OddRelation2', 'Contact', 'Organization', 'Note', 'Company') + @python_2_unicode_compatible class Link(models.Model): content_type = models.ForeignKey(ContentType) @@ -17,6 +18,7 @@ class Link(models.Model): def __str__(self): return "Link to %s id=%s" % (self.content_type, self.object_id) + @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=100) @@ -25,11 +27,13 @@ class Place(models.Model): def __str__(self): return "Place: %s" % self.name + @python_2_unicode_compatible class Restaurant(Place): def __str__(self): return "Restaurant: %s" % self.name + @python_2_unicode_compatible class Address(models.Model): street = models.CharField(max_length=80) @@ -43,6 +47,7 @@ class Address(models.Model): def __str__(self): return '%s %s, %s %s' % (self.street, self.city, self.state, self.zipcode) + @python_2_unicode_compatible class Person(models.Model): account = models.IntegerField(primary_key=True) @@ -52,24 +57,29 @@ class Person(models.Model): def __str__(self): return self.name + class CharLink(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.CharField(max_length=100) content_object = generic.GenericForeignKey() + class TextLink(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.TextField() content_object = generic.GenericForeignKey() + class OddRelation1(models.Model): name = models.CharField(max_length=100) clinks = generic.GenericRelation(CharLink) + class OddRelation2(models.Model): name = models.CharField(max_length=100) tlinks = generic.GenericRelation(TextLink) + # models for test_q_object_or: class Note(models.Model): content_type = models.ForeignKey(ContentType) @@ -77,13 +87,16 @@ class Note(models.Model): content_object = generic.GenericForeignKey() note = models.TextField() + class Contact(models.Model): notes = generic.GenericRelation(Note) + class Organization(models.Model): name = models.CharField(max_length=255) contacts = models.ManyToManyField(Contact, related_name='organizations') + @python_2_unicode_compatible class Company(models.Model): name = models.CharField(max_length=100) @@ -92,10 +105,12 @@ class Company(models.Model): def __str__(self): return "Company: %s" % self.name + # For testing #13085 fix, we also use Note model defined above class Developer(models.Model): name = models.CharField(max_length=15) + @python_2_unicode_compatible class Team(models.Model): name = models.CharField(max_length=15) @@ -107,49 +122,59 @@ class Team(models.Model): def __len__(self): return self.members.count() + class Guild(models.Model): name = models.CharField(max_length=15) members = models.ManyToManyField(Developer) def __nonzero__(self): + return self.members.count() + class Tag(models.Model): content_type = models.ForeignKey(ContentType, related_name='g_r_r_tags') object_id = models.CharField(max_length=15) content_object = generic.GenericForeignKey() label = models.CharField(max_length=15) + class Board(models.Model): name = models.CharField(primary_key=True, max_length=15) + class HasLinks(models.Model): links = generic.GenericRelation(Link) class Meta: abstract = True + class HasLinkThing(HasLinks): pass + class A(models.Model): flag = models.NullBooleanField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') + class B(models.Model): a = generic.GenericRelation(A) class Meta: ordering = ('id',) + class C(models.Model): b = models.ForeignKey(B) class Meta: ordering = ('id',) + class D(models.Model): b = models.ForeignKey(B, null=True) diff --git a/tests/generic_views/models.py b/tests/generic_views/models.py index 30c73d67ca..f5554d1a20 100644 --- a/tests/generic_views/models.py +++ b/tests/generic_views/models.py @@ -18,6 +18,7 @@ class Artist(models.Model): def get_absolute_url(self): return reverse('artist_detail', kwargs={'pk': self.id}) + @python_2_unicode_compatible class Author(models.Model): name = models.CharField(max_length=100) @@ -29,6 +30,7 @@ class Author(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Book(models.Model): name = models.CharField(max_length=300) @@ -43,9 +45,11 @@ class Book(models.Model): def __str__(self): return self.name + class Page(models.Model): content = models.TextField() template = models.CharField(max_length=300) + class BookSigning(models.Model): event_date = models.DateTimeField() diff --git a/tests/generic_views/test_base.py b/tests/generic_views/test_base.py index eafa61a271..66ce224162 100644 --- a/tests/generic_views/test_base.py +++ b/tests/generic_views/test_base.py @@ -10,6 +10,7 @@ from django.views.generic import View, TemplateView, RedirectView from . import views + class SimpleView(View): """ A simple view with a docstring. diff --git a/tests/generic_views/test_dates.py b/tests/generic_views/test_dates.py index 58ee0dfcbe..944a3dcfe3 100644 --- a/tests/generic_views/test_dates.py +++ b/tests/generic_views/test_dates.py @@ -15,9 +15,10 @@ def _make_books(n, base_date): Book.objects.create( name='Book %d' % i, slug='book-%d' % i, - pages=100+i, + pages=100 + i, pubdate=base_date - datetime.timedelta(days=i)) + class ArchiveIndexViewTests(TestCase): fixtures = ['generic-views-test-data.json'] urls = 'generic_views.urls' diff --git a/tests/generic_views/views.py b/tests/generic_views/views.py index fd88debc0f..00e74d4708 100644 --- a/tests/generic_views/views.py +++ b/tests/generic_views/views.py @@ -65,6 +65,7 @@ class CustomPaginator(Paginator): orphans=2, allow_empty_first_page=allow_empty_first_page) + class AuthorListCustomPaginator(AuthorList): paginate_by = 5 @@ -176,33 +177,42 @@ class BookConfig(object): queryset = Book.objects.all() date_field = 'pubdate' + class BookArchive(BookConfig, generic.ArchiveIndexView): pass + class BookYearArchive(BookConfig, generic.YearArchiveView): pass + class BookMonthArchive(BookConfig, generic.MonthArchiveView): pass + class BookWeekArchive(BookConfig, generic.WeekArchiveView): pass + class BookDayArchive(BookConfig, generic.DayArchiveView): pass + class BookTodayArchive(BookConfig, generic.TodayArchiveView): pass + class BookDetail(BookConfig, generic.DateDetailView): pass + class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin): fields = '__all__' def get_queryset(self): return Author.objects.all() + class BookDetailGetObjectCustomQueryset(BookDetail): def get_object(self, queryset=None): return super(BookDetailGetObjectCustomQueryset, self).get_object( @@ -234,10 +244,12 @@ class CustomContextView(generic.detail.SingleObjectMixin, generic.View): def get_context_object_name(self, obj): return "test_name" + class CustomSingleObjectView(generic.detail.SingleObjectMixin, generic.View): model = Book object = Book(name="dummy") + class BookSigningConfig(object): model = BookSigning date_field = 'event_date' @@ -246,24 +258,31 @@ class BookSigningConfig(object): def get_template_names(self): return ['generic_views/book%s.html' % self.template_name_suffix] + class BookSigningArchive(BookSigningConfig, generic.ArchiveIndexView): pass + class BookSigningYearArchive(BookSigningConfig, generic.YearArchiveView): pass + class BookSigningMonthArchive(BookSigningConfig, generic.MonthArchiveView): pass + class BookSigningWeekArchive(BookSigningConfig, generic.WeekArchiveView): pass + class BookSigningDayArchive(BookSigningConfig, generic.DayArchiveView): pass + class BookSigningTodayArchive(BookSigningConfig, generic.TodayArchiveView): pass + class BookSigningDetail(BookSigningConfig, generic.DateDetailView): context_object_name = 'book' diff --git a/tests/get_object_or_404/models.py b/tests/get_object_or_404/models.py index bb9aa60383..ea6e3e40d5 100644 --- a/tests/get_object_or_404/models.py +++ b/tests/get_object_or_404/models.py @@ -21,10 +21,12 @@ class Author(models.Model): def __str__(self): return self.name + class ArticleManager(models.Manager): def get_queryset(self): return super(ArticleManager, self).get_queryset().filter(authors__name__icontains='sir') + @python_2_unicode_compatible class Article(models.Model): authors = models.ManyToManyField(Author) diff --git a/tests/get_or_create_regress/models.py b/tests/get_or_create_regress/models.py index 637bbf62af..2ffc5c93ac 100644 --- a/tests/get_or_create_regress/models.py +++ b/tests/get_or_create_regress/models.py @@ -4,9 +4,11 @@ from django.db import models class Publisher(models.Model): name = models.CharField(max_length=100) + class Author(models.Model): name = models.CharField(max_length=100) + class Book(models.Model): name = models.CharField(max_length=100) authors = models.ManyToManyField(Author, related_name='books') diff --git a/tests/handlers/views.py b/tests/handlers/views.py index 1b75b27043..84cac97e62 100644 --- a/tests/handlers/views.py +++ b/tests/handlers/views.py @@ -4,18 +4,23 @@ from django.core.exceptions import SuspiciousOperation from django.db import connection, transaction from django.http import HttpResponse, StreamingHttpResponse + def regular(request): return HttpResponse(b"regular content") + def streaming(request): return StreamingHttpResponse([b"streaming", b" ", b"content"]) + def in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) + @transaction.non_atomic_requests def not_in_transaction(request): return HttpResponse(str(connection.in_atomic_block)) + def suspicious(request): raise SuspiciousOperation('dubious') diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index 820aecf1f7..ccea20f9c5 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -239,6 +239,7 @@ class QueryDictTests(unittest.TestCase): self.assertEqual(copy.copy(q).encoding, 'iso-8859-15') self.assertEqual(copy.deepcopy(q).encoding, 'iso-8859-15') + class HttpResponseTests(unittest.TestCase): def test_headers_type(self): @@ -414,6 +415,7 @@ class HttpResponseTests(unittest.TestCase): self.assertRaises(SuspiciousOperation, HttpResponsePermanentRedirect, url) + class HttpResponseSubclassesTests(TestCase): def test_redirect(self): response = HttpResponseRedirect('/redirected/') @@ -448,6 +450,7 @@ class HttpResponseSubclassesTests(TestCase): content_type='text/html') self.assertContains(response, 'Only the GET method is allowed', status_code=405) + class StreamingHttpResponseTests(TestCase): def test_streaming_response(self): r = StreamingHttpResponse(iter(['hello', 'world'])) @@ -501,6 +504,7 @@ class StreamingHttpResponseTests(TestCase): with self.assertRaises(Exception): r.tell() + class FileCloseTests(TestCase): def setUp(self): @@ -566,6 +570,7 @@ class FileCloseTests(TestCase): self.assertTrue(file1.closed) self.assertTrue(file2.closed) + class CookieTests(unittest.TestCase): def test_encode(self): """ diff --git a/tests/i18n/forms.py b/tests/i18n/forms.py index 07b015d590..e06ed4b18d 100644 --- a/tests/i18n/forms.py +++ b/tests/i18n/forms.py @@ -12,9 +12,11 @@ class I18nForm(forms.Form): time_field = forms.TimeField(localize=True) integer_field = forms.IntegerField(localize=True) + class SelectDateForm(forms.Form): date_field = forms.DateField(widget=SelectDateWidget) + class CompanyForm(forms.ModelForm): cents_paid = forms.DecimalField(max_digits=4, decimal_places=2, localize=True) products_delivered = forms.IntegerField(localize=True) diff --git a/tests/i18n/models.py b/tests/i18n/models.py index 6e3591de24..3afc0841c6 100644 --- a/tests/i18n/models.py +++ b/tests/i18n/models.py @@ -7,6 +7,7 @@ from django.utils.translation import ugettext_lazy as _ class TestModel(models.Model): text = models.CharField(max_length=10, default=_('Anything')) + class Company(models.Model): name = models.CharField(max_length=50) date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0)) diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index 18088e5e16..633184f7c5 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -21,6 +21,7 @@ from django.utils.translation import TranslatorCommentWarning LOCALE = 'de' has_xgettext = find_command('xgettext') + @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests') class ExtractorTests(SimpleTestCase): @@ -130,9 +131,10 @@ class BasicExtractorTests(ExtractorTests): self.assertRaises(SyntaxError, management.call_command, 'makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0) with self.assertRaises(SyntaxError) as context_manager: management.call_command('makemessages', locale=LOCALE, extensions=['tpl'], verbosity=0) - six.assertRegex(self, str(context_manager.exception), - r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)' - ) + six.assertRegex( + self, str(context_manager.exception), + r'Translation blocks must not include other block tags: blocktrans \(file templates[/\\]template_with_error\.tpl, line 3\)' + ) # Check that the temporary file was cleaned up self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py')) @@ -210,13 +212,16 @@ class BasicExtractorTests(ExtractorTests): self.assertEqual(len(ws), 3) for w in ws: self.assertTrue(issubclass(w.category, TranslatorCommentWarning)) - six.assertRegex(self, str(ws[0].message), + six.assertRegex( + self, str(ws[0].message), r"The translator-targeted comment 'Translators: ignored i18n comment #1' \(file templates[/\\]comments.thtml, line 4\) was ignored, because it wasn't the last item on the line\." ) - six.assertRegex(self, str(ws[1].message), + six.assertRegex( + self, str(ws[1].message), r"The translator-targeted comment 'Translators: ignored i18n comment #3' \(file templates[/\\]comments.thtml, line 6\) was ignored, because it wasn't the last item on the line\." ) - six.assertRegex(self, str(ws[2].message), + six.assertRegex( + self, str(ws[2].message), r"The translator-targeted comment 'Translators: ignored i18n comment #4' \(file templates[/\\]comments.thtml, line 8\) was ignored, because it wasn't the last item on the line\." ) # Now test .po file contents @@ -281,6 +286,7 @@ class JavascriptExtractorTests(ExtractorTests): self.assertMsgId("quz", po_contents) self.assertMsgId("foobar", po_contents) + class IgnoredExtractorTests(ExtractorTests): def test_ignore_option(self): diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py index b1f3de0ef9..ac9242241d 100644 --- a/tests/i18n/tests.py +++ b/tests/i18n/tests.py @@ -956,12 +956,14 @@ class ResolutionOrderI18NTests(TransRealMixin, TestCase): self.assertTrue(msgstr in result, ("The string '%s' isn't in the " "translation of '%s'; the actual result is '%s'." % (msgstr, msgid, result))) + @override_settings(INSTALLED_APPS=['i18n.resolution'] + list(settings.INSTALLED_APPS)) class AppResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_app_translation(self): self.assertUgettext('Date/time', 'APP') + @override_settings(LOCALE_PATHS=extended_locale_paths) class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): @@ -973,6 +975,7 @@ class LocalePathsResolutionOrderI18NTests(ResolutionOrderI18NTests): with self.settings(INSTALLED_APPS=extended_apps): self.assertUgettext('Time', 'LOCALE_PATHS') + class DjangoFallbackResolutionOrderI18NTests(ResolutionOrderI18NTests): def test_django_fallback(self): diff --git a/tests/inline_formsets/models.py b/tests/inline_formsets/models.py index 40c85fe739..383122dbd7 100644 --- a/tests/inline_formsets/models.py +++ b/tests/inline_formsets/models.py @@ -6,15 +6,18 @@ from django.utils.encoding import python_2_unicode_compatible class School(models.Model): name = models.CharField(max_length=100) + class Parent(models.Model): name = models.CharField(max_length=100) + class Child(models.Model): mother = models.ForeignKey(Parent, related_name='mothers_children') father = models.ForeignKey(Parent, related_name='fathers_children') school = models.ForeignKey(School) name = models.CharField(max_length=100) + @python_2_unicode_compatible class Poet(models.Model): name = models.CharField(max_length=100) @@ -22,6 +25,7 @@ class Poet(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Poem(models.Model): poet = models.ForeignKey(Poet) diff --git a/tests/inspectdb/models.py b/tests/inspectdb/models.py index 83cd906a07..f7c8af73c6 100644 --- a/tests/inspectdb/models.py +++ b/tests/inspectdb/models.py @@ -9,22 +9,27 @@ class People(models.Model): name = models.CharField(max_length=255) parent = models.ForeignKey('self') + class Message(models.Model): from_field = models.ForeignKey(People, db_column='from_id') + class PeopleData(models.Model): people_pk = models.ForeignKey(People, primary_key=True) ssn = models.CharField(max_length=11) + class PeopleMoreData(models.Model): people_unique = models.ForeignKey(People, unique=True) license = models.CharField(max_length=255) + class DigitsInColumnName(models.Model): all_digits = models.CharField(max_length=11, db_column='123') leading_digit = models.CharField(max_length=11, db_column='4extra') leading_digits = models.CharField(max_length=11, db_column='45extra') + class SpecialColumnName(models.Model): field = models.IntegerField(db_column='field') # Underscores @@ -35,6 +40,7 @@ class SpecialColumnName(models.Model): prc_x = models.IntegerField(db_column='prc(%) x') non_ascii = models.IntegerField(db_column='tamaño') + class ColumnTypes(models.Model): id = models.AutoField(primary_key=True) big_int_field = models.BigIntegerField() diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py index 82802843d9..abd43f10e3 100644 --- a/tests/inspectdb/tests.py +++ b/tests/inspectdb/tests.py @@ -14,6 +14,7 @@ if connection.vendor == 'oracle': else: expectedFailureOnOracle = lambda f: f + class InspectDBTestCase(TestCase): def test_stealth_table_name_filter_option(self): @@ -166,7 +167,7 @@ class InspectDBTestCase(TestCase): self.assertIn(" managed = False", output, msg='inspectdb should generate unmanaged models.') @skipUnless(connection.vendor == 'sqlite', - "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test") + "Only patched sqlite's DatabaseIntrospection.data_types_reverse for this test") def test_custom_fields(self): """ Introspection of columns with a custom field (#21090) diff --git a/tests/known_related_objects/models.py b/tests/known_related_objects/models.py index cfee4650d9..2b5ab6cfe5 100644 --- a/tests/known_related_objects/models.py +++ b/tests/known_related_objects/models.py @@ -6,17 +6,21 @@ Test that queries are not redone when going back through known relations. from django.db import models + class Tournament(models.Model): name = models.CharField(max_length=30) + class Organiser(models.Model): name = models.CharField(max_length=30) + class Pool(models.Model): name = models.CharField(max_length=30) tournament = models.ForeignKey(Tournament) organiser = models.ForeignKey(Organiser) + class PoolStyle(models.Model): name = models.CharField(max_length=30) pool = models.OneToOneField(Pool) diff --git a/tests/known_related_objects/tests.py b/tests/known_related_objects/tests.py index 6fd507cbdc..03307f49ac 100644 --- a/tests/known_related_objects/tests.py +++ b/tests/known_related_objects/tests.py @@ -4,6 +4,7 @@ from django.test import TestCase from .models import Tournament, Organiser, Pool, PoolStyle + class ExistingRelatedInstancesTests(TestCase): fixtures = ['tournament.json'] diff --git a/tests/logging_tests/tests.py b/tests/logging_tests/tests.py index bd1983f74e..1b3a20cc24 100644 --- a/tests/logging_tests/tests.py +++ b/tests/logging_tests/tests.py @@ -62,6 +62,7 @@ class LoggingFiltersTest(TestCase): with self.settings(DEBUG=False): self.assertEqual(filter_.filter("record is not used"), False) + class DefaultLoggingTest(TestCase): def setUp(self): self.logger = logging.getLogger('django') @@ -83,6 +84,7 @@ class DefaultLoggingTest(TestCase): self.logger.error("Hey, this is an error.") self.assertEqual(output.getvalue(), 'Hey, this is an error.\n') + class WarningLoggerTests(TestCase): """ Tests that warnings output for DeprecationWarnings is enabled diff --git a/tests/lookup/models.py b/tests/lookup/models.py index a130d35e8e..df8b26c4e9 100644 --- a/tests/lookup/models.py +++ b/tests/lookup/models.py @@ -17,6 +17,7 @@ class Author(models.Model): class Meta: ordering = ('name', ) + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) @@ -29,6 +30,7 @@ class Article(models.Model): def __str__(self): return self.headline + class Tag(models.Model): articles = models.ManyToManyField(Article) name = models.CharField(max_length=100) @@ -36,6 +38,7 @@ class Tag(models.Model): class Meta: ordering = ('name', ) + @python_2_unicode_compatible class Season(models.Model): year = models.PositiveSmallIntegerField() @@ -44,6 +47,7 @@ class Season(models.Model): def __str__(self): return six.text_type(self.year) + @python_2_unicode_compatible class Game(models.Model): season = models.ForeignKey(Season, related_name='games') @@ -53,6 +57,7 @@ class Game(models.Model): def __str__(self): return "%s at %s" % (self.away, self.home) + @python_2_unicode_compatible class Player(models.Model): name = models.CharField(max_length=100) diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py index c303743f04..482ae9a1fa 100644 --- a/tests/m2m_and_m2o/models.py +++ b/tests/m2m_and_m2o/models.py @@ -13,6 +13,7 @@ from django.utils.encoding import python_2_unicode_compatible class User(models.Model): username = models.CharField(max_length=20) + @python_2_unicode_compatible class Issue(models.Model): num = models.IntegerField() @@ -25,5 +26,6 @@ class Issue(models.Model): class Meta: ordering = ('num',) + class UnicodeReferenceModel(models.Model): others = models.ManyToManyField("UnicodeReferenceModel") diff --git a/tests/m2m_and_m2o/tests.py b/tests/m2m_and_m2o/tests.py index 35443e32e4..e950a839d2 100644 --- a/tests/m2m_and_m2o/tests.py +++ b/tests/m2m_and_m2o/tests.py @@ -50,7 +50,7 @@ class RelatedObjectTests(TestCase): # These queries combine results from the m2m and the m2o relationships. # They're three ways of saying the same thing. self.assertQuerysetEqual( - Issue.objects.filter(Q(cc__id__exact = r.id) | Q(client=r.id)), [ + Issue.objects.filter(Q(cc__id__exact=r.id) | Q(client=r.id)), [ 1, 2, 3, @@ -74,6 +74,7 @@ class RelatedObjectTests(TestCase): lambda i: i.num ) + class RelatedObjectUnicodeTests(TestCase): def test_m2m_with_unicode_reference(self): """ diff --git a/tests/m2m_intermediary/models.py b/tests/m2m_intermediary/models.py index 770681f91c..9b194e321b 100644 --- a/tests/m2m_intermediary/models.py +++ b/tests/m2m_intermediary/models.py @@ -23,6 +23,7 @@ class Reporter(models.Model): def __str__(self): return "%s %s" % (self.first_name, self.last_name) + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) @@ -31,6 +32,7 @@ class Article(models.Model): def __str__(self): return self.headline + @python_2_unicode_compatible class Writer(models.Model): reporter = models.ForeignKey(Reporter) diff --git a/tests/m2m_regress/models.py b/tests/m2m_regress/models.py index abd012b3d0..48fdad9304 100644 --- a/tests/m2m_regress/models.py +++ b/tests/m2m_regress/models.py @@ -2,6 +2,7 @@ from django.contrib.auth import models as auth from django.db import models from django.utils.encoding import python_2_unicode_compatible + # No related name is needed here, since symmetrical relations are not # explicitly reversible. @python_2_unicode_compatible @@ -13,6 +14,7 @@ class SelfRefer(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Tag(models.Model): name = models.CharField(max_length=10) @@ -20,6 +22,7 @@ class Tag(models.Model): def __str__(self): return self.name + # Regression for #11956 -- a many to many to the base class @python_2_unicode_compatible class TagCollection(Tag): @@ -28,6 +31,7 @@ class TagCollection(Tag): def __str__(self): return self.name + # A related_name is required on one of the ManyToManyField entries here because # they are both addressable as reverse relations from Tag. @python_2_unicode_compatible @@ -39,21 +43,26 @@ class Entry(models.Model): def __str__(self): return self.name + # Two models both inheriting from a base model with a self-referential m2m field class SelfReferChild(SelfRefer): pass + class SelfReferChildSibling(SelfRefer): pass + # Many-to-Many relation between models, where one of the PK's isn't an Autofield class Line(models.Model): name = models.CharField(max_length=100) + class Worksheet(models.Model): id = models.CharField(primary_key=True, max_length=100) lines = models.ManyToManyField(Line, blank=True, null=True) + # Regression for #11226 -- A model with the same name that another one to # which it has a m2m relation. This shouldn't cause a name clash between # the automatically created m2m intermediary table FK field names when diff --git a/tests/m2m_signals/models.py b/tests/m2m_signals/models.py index e997d87f21..e4110ccf34 100644 --- a/tests/m2m_signals/models.py +++ b/tests/m2m_signals/models.py @@ -12,6 +12,7 @@ class Part(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Car(models.Model): name = models.CharField(max_length=20) @@ -24,9 +25,11 @@ class Car(models.Model): def __str__(self): return self.name + class SportsCar(Car): price = models.IntegerField() + @python_2_unicode_compatible class Person(models.Model): name = models.CharField(max_length=20) diff --git a/tests/m2m_through/models.py b/tests/m2m_through/models.py index a896f6d9ff..70d6baeca8 100644 --- a/tests/m2m_through/models.py +++ b/tests/m2m_through/models.py @@ -15,6 +15,7 @@ class Person(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Group(models.Model): name = models.CharField(max_length=128) @@ -28,6 +29,7 @@ class Group(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Membership(models.Model): person = models.ForeignKey(Person) @@ -41,6 +43,7 @@ class Membership(models.Model): def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) + @python_2_unicode_compatible class CustomMembership(models.Model): person = models.ForeignKey(Person, db_column="custom_person_column", related_name="custom_person_related_name") @@ -54,11 +57,13 @@ class CustomMembership(models.Model): class Meta: db_table = "test_table" + class TestNoDefaultsOrNulls(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) nodefaultnonull = models.CharField(max_length=5) + @python_2_unicode_compatible class PersonSelfRefM2M(models.Model): name = models.CharField(max_length=5) @@ -67,6 +72,7 @@ class PersonSelfRefM2M(models.Model): def __str__(self): return self.name + class Friendship(models.Model): first = models.ForeignKey(PersonSelfRefM2M, related_name="rel_from_set") second = models.ForeignKey(PersonSelfRefM2M, related_name="rel_to_set") diff --git a/tests/m2m_through_regress/models.py b/tests/m2m_through_regress/models.py index 91e1aa8cc1..c49e5b02eb 100644 --- a/tests/m2m_through_regress/models.py +++ b/tests/m2m_through_regress/models.py @@ -15,6 +15,7 @@ class Membership(models.Model): def __str__(self): return "%s is a member of %s" % (self.person.name, self.group.name) + # using custom id column to test ticket #11107 @python_2_unicode_compatible class UserMembership(models.Model): @@ -26,6 +27,7 @@ class UserMembership(models.Model): def __str__(self): return "%s is a user and member of %s" % (self.user.username, self.group.name) + @python_2_unicode_compatible class Person(models.Model): name = models.CharField(max_length=128) @@ -33,6 +35,7 @@ class Person(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Group(models.Model): name = models.CharField(max_length=128) @@ -43,17 +46,21 @@ class Group(models.Model): def __str__(self): return self.name + # A set of models that use an non-abstract inherited model as the 'through' model. class A(models.Model): a_text = models.CharField(max_length=20) + class ThroughBase(models.Model): a = models.ForeignKey(A) b = models.ForeignKey('B') + class Through(ThroughBase): extra = models.CharField(max_length=20) + class B(models.Model): b_text = models.CharField(max_length=20) a_list = models.ManyToManyField(A, through=Through) @@ -68,6 +75,7 @@ class Car(models.Model): def __str__(self): return "%s" % self.make + @python_2_unicode_compatible class Driver(models.Model): name = models.CharField(max_length=20, unique=True, null=True) @@ -78,6 +86,7 @@ class Driver(models.Model): class Meta: ordering = ('name',) + @python_2_unicode_compatible class CarDriver(models.Model): car = models.ForeignKey('Car', to_field='make') diff --git a/tests/m2o_recursive/models.py b/tests/m2o_recursive/models.py index 2775d713dd..b41e0cb0a3 100644 --- a/tests/m2o_recursive/models.py +++ b/tests/m2o_recursive/models.py @@ -22,6 +22,7 @@ class Category(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Person(models.Model): full_name = models.CharField(max_length=20) diff --git a/tests/m2o_recursive/tests.py b/tests/m2o_recursive/tests.py index f5e8938706..b21aef95d3 100644 --- a/tests/m2o_recursive/tests.py +++ b/tests/m2o_recursive/tests.py @@ -21,6 +21,7 @@ class ManyToOneRecursiveTests(TestCase): self.assertQuerysetEqual(self.c.child_set.all(), []) self.assertEqual(self.c.parent.id, self.r.id) + class MultipleManyToOneRecursiveTests(TestCase): def setUp(self): diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py index 31793b3974..eaf98ce565 100644 --- a/tests/many_to_many/models.py +++ b/tests/many_to_many/models.py @@ -22,6 +22,7 @@ class Publication(models.Model): class Meta: ordering = ('title',) + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py index 4e2ed67eea..8c50ffe53b 100644 --- a/tests/many_to_one/models.py +++ b/tests/many_to_one/models.py @@ -18,6 +18,7 @@ class Reporter(models.Model): def __str__(self): return "%s %s" % (self.first_name, self.last_name) + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) diff --git a/tests/many_to_one_null/models.py b/tests/many_to_one_null/models.py index e00ca85928..16ee56cec6 100644 --- a/tests/many_to_one_null/models.py +++ b/tests/many_to_one_null/models.py @@ -16,6 +16,7 @@ class Reporter(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) diff --git a/tests/many_to_one_regress/models.py b/tests/many_to_one_regress/models.py index 0ac0871793..c94bc5e05c 100644 --- a/tests/many_to_one_regress/models.py +++ b/tests/many_to_one_regress/models.py @@ -10,21 +10,26 @@ from django.utils.encoding import python_2_unicode_compatible # created (the field names being lower-cased versions of their opposite # classes is important here). + class First(models.Model): second = models.IntegerField() + class Second(models.Model): - first = models.ForeignKey(First, related_name = 'the_first') + first = models.ForeignKey(First, related_name='the_first') + # Protect against repetition of #1839, #2415 and #2536. class Third(models.Model): name = models.CharField(max_length=20) third = models.ForeignKey('self', null=True, related_name='child_set') + class Parent(models.Model): name = models.CharField(max_length=20) bestchild = models.ForeignKey('Child', null=True, related_name='favored_by') + class Child(models.Model): name = models.CharField(max_length=20) parent = models.ForeignKey(Parent) @@ -38,9 +43,11 @@ class Category(models.Model): def __str__(self): return self.name + class Record(models.Model): category = models.ForeignKey(Category) + @python_2_unicode_compatible class Relation(models.Model): left = models.ForeignKey(Record, related_name='left_set') @@ -49,8 +56,10 @@ class Relation(models.Model): def __str__(self): return "%s - %s" % (self.left.category.name, self.right.category.name) + class Car(models.Model): make = models.CharField(max_length=100, null=True, unique=True) + class Driver(models.Model): car = models.ForeignKey(Car, to_field='make', null=True, related_name='drivers') diff --git a/tests/max_lengths/models.py b/tests/max_lengths/models.py index d66e833e8c..ec4cc8e114 100644 --- a/tests/max_lengths/models.py +++ b/tests/max_lengths/models.py @@ -7,6 +7,7 @@ class PersonWithDefaultMaxLengths(models.Model): homepage = models.URLField() avatar = models.FilePathField() + class PersonWithCustomMaxLengths(models.Model): email = models.EmailField(max_length=250) vcard = models.FileField(upload_to='/tmp', max_length=250) diff --git a/tests/max_lengths/tests.py b/tests/max_lengths/tests.py index 5dd33fc80f..25101cd535 100644 --- a/tests/max_lengths/tests.py +++ b/tests/max_lengths/tests.py @@ -22,6 +22,7 @@ class MaxLengthArgumentsTests(unittest.TestCase): self.verify_max_length(PersonWithCustomMaxLengths, 'homepage', 250) self.verify_max_length(PersonWithCustomMaxLengths, 'avatar', 250) + class MaxLengthORMTests(unittest.TestCase): def test_custom_max_lengths(self): diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index b474f6b0e3..0124e33c98 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -120,7 +120,7 @@ class CommonMiddlewareTest(TestCase): r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, - 'http://www.testserver/middleware/slash/') + 'http://www.testserver/middleware/slash/') @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_slashless(self): @@ -128,7 +128,7 @@ class CommonMiddlewareTest(TestCase): r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, - 'http://www.testserver/middleware/slash/') + 'http://www.testserver/middleware/slash/') # The following tests examine expected behavior given a custom urlconf that # overrides the default one through the request object. @@ -228,7 +228,7 @@ class CommonMiddlewareTest(TestCase): r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, - 'http://www.testserver/middleware/customurlconf/slash/') + 'http://www.testserver/middleware/customurlconf/slash/') @override_settings(APPEND_SLASH=True, PREPEND_WWW=True) def test_prepend_www_append_slash_slashless_custom_urlconf(self): @@ -237,7 +237,7 @@ class CommonMiddlewareTest(TestCase): r = CommonMiddleware().process_request(request) self.assertEqual(r.status_code, 301) self.assertEqual(r.url, - 'http://www.testserver/middleware/customurlconf/slash/') + 'http://www.testserver/middleware/customurlconf/slash/') # Legacy tests for the 404 error reporting via email (to be removed in 1.8) @@ -336,7 +336,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase): return True user_agent = request.META['HTTP_USER_AGENT'] return any(pattern.search(user_agent) for pattern in - self.ignored_user_agent_patterns) + self.ignored_user_agent_patterns) self.req.META['HTTP_REFERER'] = '/another/url/' self.req.META['HTTP_USER_AGENT'] = 'Spider machine 3.4' @@ -346,6 +346,7 @@ class BrokenLinkEmailsMiddlewareTest(TestCase): SubclassedMiddleware().process_response(self.req, self.resp) self.assertEqual(len(mail.outbox), 1) + class ConditionalGetMiddlewareTest(TestCase): urls = 'middleware.cond_get_urls' @@ -704,6 +705,7 @@ class ETagGZipMiddlewareTest(TestCase): self.assertNotEqual(gzip_etag, nogzip_etag) + class TransactionMiddlewareTest(IgnoreDeprecationWarningsMixin, TransactionTestCase): """ Test the transaction middleware. diff --git a/tests/middleware_exceptions/tests.py b/tests/middleware_exceptions/tests.py index 02e53a00e8..83c6118c9d 100644 --- a/tests/middleware_exceptions/tests.py +++ b/tests/middleware_exceptions/tests.py @@ -778,6 +778,8 @@ class BadMiddlewareTests(BaseMiddlewareExceptionTest): _missing = object() + + class RootUrlconfTests(TestCase): urls = 'middleware_exceptions.urls' diff --git a/tests/middleware_exceptions/views.py b/tests/middleware_exceptions/views.py index ddf28c46a3..59abe26bff 100644 --- a/tests/middleware_exceptions/views.py +++ b/tests/middleware_exceptions/views.py @@ -7,20 +7,26 @@ from django.template.response import TemplateResponse def normal_view(request): return http.HttpResponse('OK') + def template_response(request): return TemplateResponse(request, Template('OK')) + def template_response_error(request): return TemplateResponse(request, Template('{%')) + def not_found(request): raise http.Http404() + def server_error(request): raise Exception('Error in view') + def null_view(request): return None + def permission_denied(request): raise PermissionDenied() diff --git a/tests/model_fields/tests.py b/tests/model_fields/tests.py index f3ef83a39c..d78f3d7c2d 100644 --- a/tests/model_fields/tests.py +++ b/tests/model_fields/tests.py @@ -133,6 +133,7 @@ class DecimalFieldTests(test.TestCase): # This should not crash. That counts as a win for our purposes. Foo.objects.filter(d__gte=100000000000) + class ForeignKeyTests(test.TestCase): def test_callable_default(self): """Test the use of a lazy callable for ForeignKey.default""" @@ -140,6 +141,7 @@ class ForeignKeyTests(test.TestCase): b = Bar.objects.create(b="bcd") self.assertEqual(b.a, a) + class DateTimeFieldTests(unittest.TestCase): def test_datetimefield_to_python_usecs(self): """DateTimeField.to_python should support usecs""" @@ -157,6 +159,7 @@ class DateTimeFieldTests(unittest.TestCase): self.assertEqual(f.to_python('01:02:03.999999'), datetime.time(1, 2, 3, 999999)) + class BooleanFieldTests(unittest.TestCase): def _test_get_db_prep_lookup(self, f): from django.db import connection @@ -294,6 +297,7 @@ class BooleanFieldTests(unittest.TestCase): self.assertIsNone(nb.nbfield) nb.save() # no error + class ChoicesTests(test.TestCase): def test_choices_and_field_display(self): """ @@ -306,6 +310,7 @@ class ChoicesTests(test.TestCase): self.assertEqual(Whiz(c=None).get_c_display(), None) # Blank value self.assertEqual(Whiz(c='').get_c_display(), '') # Empty value + class SlugFieldTests(test.TestCase): def test_slugfield_max_length(self): """ @@ -409,6 +414,7 @@ class BigIntegerFieldTests(test.TestCase): b = BigInt.objects.get(value='10') self.assertEqual(b.value, 10) + class TypeCoercionTests(test.TestCase): """ Test that database lookups can accept the wrong types and convert @@ -422,6 +428,7 @@ class TypeCoercionTests(test.TestCase): def test_lookup_integer_in_textfield(self): self.assertEqual(Post.objects.filter(body=24).count(), 0) + class FileFieldTests(unittest.TestCase): def test_clearable(self): """ @@ -496,6 +503,7 @@ class BinaryFieldTests(test.TestCase): dm = DataModel(short_data=self.binary_data * 4) self.assertRaises(ValidationError, dm.full_clean) + class GenericIPAddressFieldTests(test.TestCase): def test_genericipaddressfield_formfield_protocol(self): """ diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py index 34644a4bb9..72bf1ff26a 100644 --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -34,6 +34,7 @@ ARTICLE_STATUS_CHAR = ( ('l', 'Live'), ) + @python_2_unicode_compatible class Category(models.Model): name = models.CharField(max_length=20) @@ -46,6 +47,7 @@ class Category(models.Model): def __repr__(self): return self.__str__() + @python_2_unicode_compatible class Writer(models.Model): name = models.CharField(max_length=50, help_text='Use both first and last names.') @@ -56,6 +58,7 @@ class Writer(models.Model): def __str__(self): return self.name + @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=50) @@ -76,15 +79,19 @@ class Article(models.Model): def __str__(self): return self.headline + class ImprovedArticle(models.Model): article = models.OneToOneField(Article) + class ImprovedArticleWithParentLink(models.Model): article = models.OneToOneField(Article, parent_link=True) + class BetterWriter(Writer): score = models.IntegerField() + @python_2_unicode_compatible class WriterProfile(models.Model): writer = models.OneToOneField(Writer, primary_key=True) @@ -93,6 +100,7 @@ class WriterProfile(models.Model): def __str__(self): return "%s is %s" % (self.writer, self.age) + @python_2_unicode_compatible class TextFile(models.Model): description = models.CharField(max_length=20) @@ -144,6 +152,7 @@ try: except ImproperlyConfigured: test_images = False + @python_2_unicode_compatible class CommaSeparatedInteger(models.Model): field = models.CommaSeparatedIntegerField(max_length=20) @@ -151,6 +160,7 @@ class CommaSeparatedInteger(models.Model): def __str__(self): return self.field + @python_2_unicode_compatible class Product(models.Model): slug = models.SlugField(unique=True) @@ -158,6 +168,7 @@ class Product(models.Model): def __str__(self): return self.slug + @python_2_unicode_compatible class Price(models.Model): price = models.DecimalField(max_digits=10, decimal_places=2) @@ -169,9 +180,11 @@ class Price(models.Model): class Meta: unique_together = (('price', 'quantity'),) + class ArticleStatus(models.Model): status = models.CharField(max_length=2, choices=ARTICLE_STATUS_CHAR, blank=True, null=True) + @python_2_unicode_compatible class Inventory(models.Model): barcode = models.PositiveIntegerField(unique=True) @@ -187,6 +200,7 @@ class Inventory(models.Model): def __repr__(self): return self.__str__() + class Book(models.Model): title = models.CharField(max_length=40) author = models.ForeignKey(Writer, blank=True, null=True) @@ -195,6 +209,7 @@ class Book(models.Model): class Meta: unique_together = ('title', 'author') + class BookXtra(models.Model): isbn = models.CharField(max_length=16, unique=True) suffix1 = models.IntegerField(blank=True, default=0) @@ -204,9 +219,11 @@ class BookXtra(models.Model): unique_together = (('suffix1', 'suffix2')) abstract = True + class DerivedBook(Book, BookXtra): pass + @python_2_unicode_compatible class ExplicitPK(models.Model): key = models.CharField(max_length=20, primary_key=True) @@ -218,6 +235,7 @@ class ExplicitPK(models.Model): def __str__(self): return self.key + @python_2_unicode_compatible class Post(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) @@ -228,6 +246,7 @@ class Post(models.Model): def __str__(self): return self.title + @python_2_unicode_compatible class DateTimePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) @@ -238,9 +257,11 @@ class DateTimePost(models.Model): def __str__(self): return self.title + class DerivedPost(Post): pass + @python_2_unicode_compatible class BigInt(models.Model): biggie = models.BigIntegerField() @@ -248,6 +269,7 @@ class BigInt(models.Model): def __str__(self): return six.text_type(self.biggie) + class MarkupField(models.CharField): def __init__(self, *args, **kwargs): kwargs["max_length"] = 20 @@ -260,16 +282,19 @@ class MarkupField(models.CharField): # regressed at r10062 return None + class CustomFieldForExclusionModel(models.Model): name = models.CharField(max_length=10) markup = MarkupField() + class FlexibleDatePost(models.Model): title = models.CharField(max_length=50, unique_for_date='posted', blank=True) slug = models.CharField(max_length=50, unique_for_year='posted', blank=True) subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True) posted = models.DateField(blank=True, null=True) + @python_2_unicode_compatible class Colour(models.Model): name = models.CharField(max_length=50) @@ -281,14 +306,17 @@ class Colour(models.Model): def __str__(self): return self.name + class ColourfulItem(models.Model): name = models.CharField(max_length=50) colours = models.ManyToManyField(Colour) + class ArticleStatusNote(models.Model): name = models.CharField(max_length=20) status = models.ManyToManyField(ArticleStatus) + class CustomErrorMessage(models.Model): name1 = models.CharField(max_length=50, validators=[validators.validate_slug], diff --git a/tests/model_inheritance_same_model_name/models.py b/tests/model_inheritance_same_model_name/models.py index 8b02b08668..a8c051facf 100644 --- a/tests/model_inheritance_same_model_name/models.py +++ b/tests/model_inheritance_same_model_name/models.py @@ -11,6 +11,7 @@ from django.db import models from model_inheritance.models import NamedURL from django.utils.encoding import python_2_unicode_compatible + # # Abstract base classes with related models # diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index 8596346c7e..222d236bb0 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -215,23 +215,23 @@ class QueryTestCase(TestCase): # Remove the second author dive.authors.remove(john) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + []) # Clear all authors dive.authors.clear() self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) + []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='John Smith').values_list('title', flat=True)), - []) + []) # Create an author through the m2m interface dive.authors.create(name='Jane Brown') self.assertEqual(list(Book.objects.using('other').filter(authors__name='Mark Pilgrim').values_list('title', flat=True)), - []) + []) self.assertEqual(list(Book.objects.using('other').filter(authors__name='Jane Brown').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) def test_m2m_reverse_operations(self): "M2M reverse manipulations are all constrained to a single DB" @@ -251,42 +251,42 @@ class QueryTestCase(TestCase): # Add a books to the m2m mark.book_set.add(grease) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) # Remove a book from the m2m mark.book_set.remove(grease) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - []) + []) # Clear the books associated with mark mark.book_set.clear() self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(book__title='Greasemonkey Hacks').values_list('name', flat=True)), - []) + []) # Create a book through the m2m interface mark.book_set.create(title="Dive into HTML5", published=datetime.date(2020, 1, 1)) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into Python').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(book__title='Dive into HTML5').values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) def test_m2m_cross_database_protection(self): "Operations that involve sharing M2M objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) + published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") # Set a foreign key set with an object from a different database @@ -413,14 +413,14 @@ class QueryTestCase(TestCase): # Check that queries work across foreign key joins self.assertEqual(list(Person.objects.using('default').filter(edited__title='Pro Django').values_list('name', flat=True)), - ['George Vilches']) + ['George Vilches']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Pro Django').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('default').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + ['Chris Mills']) # Reget the objects to clear caches chris = Person.objects.using('other').get(name="Chris Mills") @@ -428,12 +428,12 @@ class QueryTestCase(TestCase): # Retrive related object by descriptor. Related objects should be database-baound self.assertEqual(list(chris.edited.values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) def test_foreign_key_reverse_operations(self): "FK reverse manipulations are all constrained to a single DB" dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + published=datetime.date(2009, 5, 4)) chris = Person.objects.using('other').create(name="Chris Mills") @@ -444,48 +444,48 @@ class QueryTestCase(TestCase): # Add a second book edited by chris html5 = Book.objects.using('other').create(title="Dive into HTML5", published=datetime.date(2010, 3, 15)) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) + []) chris.edited.add(html5) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - ['Chris Mills']) + ['Chris Mills']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + ['Chris Mills']) # Remove the second editor chris.edited.remove(html5) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - ['Chris Mills']) + ['Chris Mills']) # Clear all edited books chris.edited.clear() self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) + []) # Create an author through the m2m interface chris.edited.create(title='Dive into Water', published=datetime.date(2010, 3, 15)) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into HTML5').values_list('name', flat=True)), - []) + []) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Water').values_list('name', flat=True)), - ['Chris Mills']) + ['Chris Mills']) self.assertEqual(list(Person.objects.using('other').filter(edited__title='Dive into Python').values_list('name', flat=True)), - []) + []) def test_foreign_key_cross_database_protection(self): "Operations that involve sharing FK objects across databases raise an error" # Create a book and author on the default database pro = Book.objects.create(title="Pro Django", - published=datetime.date(2008, 12, 16)) + published=datetime.date(2008, 12, 16)) marty = Person.objects.create(name="Marty Alchin") # Create a book and author on the other database dive = Book.objects.using('other').create(title="Dive into Python", - published=datetime.date(2009, 5, 4)) + published=datetime.date(2009, 5, 4)) mark = Person.objects.using('other').create(name="Mark Pilgrim") @@ -529,37 +529,37 @@ class QueryTestCase(TestCase): self.assertEqual(html5._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Person.objects.using('other').values_list('name', flat=True)), - ['Mark Pilgrim']) + ['Mark Pilgrim']) self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)), - ['Dive into Python']) + ['Dive into Python']) # When saved (no using required), new objects goes to 'other' chris.save() html5.save() self.assertEqual(list(Person.objects.using('default').values_list('name', flat=True)), - ['Marty Alchin']) + ['Marty Alchin']) self.assertEqual(list(Person.objects.using('other').values_list('name', flat=True)), - ['Chris Mills', 'Mark Pilgrim']) + ['Chris Mills', 'Mark Pilgrim']) self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)), - ['Pro Django']) + ['Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)), - ['Dive into HTML5', 'Dive into Python']) + ['Dive into HTML5', 'Dive into Python']) # This also works if you assign the FK in the constructor water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark) self.assertEqual(water._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)), - ['Pro Django']) + ['Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)), - ['Dive into HTML5', 'Dive into Python']) + ['Dive into HTML5', 'Dive into Python']) # When saved, the new book goes to 'other' water.save() self.assertEqual(list(Book.objects.using('default').values_list('title', flat=True)), - ['Pro Django']) + ['Pro Django']) self.assertEqual(list(Book.objects.using('other').values_list('title', flat=True)), - ['Dive into HTML5', 'Dive into Python', 'Dive into Water']) + ['Dive into HTML5', 'Dive into Python', 'Dive into Water']) def test_foreign_key_deletion(self): "Cascaded deletions of Foreign Key relations issue queries on the right database" @@ -608,14 +608,14 @@ class QueryTestCase(TestCase): # Check that queries work across joins self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), - ['alice']) + ['alice']) self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='chocolate').values_list('username', flat=True)), - []) + []) self.assertEqual(list(User.objects.using('default').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), - []) + []) self.assertEqual(list(User.objects.using('other').filter(userprofile__flavor='crunchy frog').values_list('username', flat=True)), - ['bob']) + ['bob']) # Reget the objects to clear caches alice_profile = UserProfile.objects.using('default').get(flavor='chocolate') @@ -664,22 +664,22 @@ class QueryTestCase(TestCase): # ... but it isn't saved yet self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), - ['bob']) + ['bob']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog']) + ['crunchy frog']) # When saved (no using required), new objects goes to 'other' charlie.save() bob_profile.save() new_bob_profile.save() self.assertEqual(list(User.objects.using('default').values_list('username', flat=True)), - ['alice']) + ['alice']) self.assertEqual(list(User.objects.using('other').values_list('username', flat=True)), - ['bob', 'charlie']) + ['bob', 'charlie']) self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) + ['chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise']) + ['crunchy frog', 'spring surprise']) # This also works if you assign the O2O relation in the constructor denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com') @@ -688,16 +688,16 @@ class QueryTestCase(TestCase): self.assertEqual(denise_profile._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) + ['chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise']) + ['crunchy frog', 'spring surprise']) # When saved, the new profile goes to 'other' denise_profile.save() self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor', flat=True)), - ['chocolate']) + ['chocolate']) self.assertEqual(list(UserProfile.objects.using('other').values_list('flavor', flat=True)), - ['crunchy frog', 'spring surprise', 'tofu']) + ['crunchy frog', 'spring surprise', 'tofu']) def test_generic_key_separation(self): "Generic fields are constrained to a single database" @@ -724,7 +724,7 @@ class QueryTestCase(TestCase): # Retrive related object by descriptor. Related objects should be database-bound self.assertEqual(list(dive.reviews.all().values_list('source', flat=True)), - ['Python Weekly']) + ['Python Weekly']) def test_generic_key_reverse_operations(self): "Generic reverse manipulations are all constrained to a single DB" @@ -738,37 +738,37 @@ class QueryTestCase(TestCase): review2 = Review.objects.using('other').create(source="Python Monthly", content_object=temp) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Weekly']) + ['Python Weekly']) # Add a second review dive.reviews.add(review2) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Monthly', 'Python Weekly']) + ['Python Monthly', 'Python Weekly']) # Remove the second author dive.reviews.remove(review1) self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Monthly']) + ['Python Monthly']) # Clear all reviews dive.reviews.clear() self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) # Create an author through the generic interface dive.reviews.create(source='Python Daily') self.assertEqual(list(Review.objects.using('default').filter(object_id=dive.pk).values_list('source', flat=True)), - []) + []) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Daily']) + ['Python Daily']) def test_generic_key_cross_database_protection(self): "Operations that involve sharing generic key objects across databases raise an error" @@ -810,16 +810,16 @@ class QueryTestCase(TestCase): self.assertEqual(review3._state.db, 'other') # ... but it isn't saved yet self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), - ['Python Monthly']) + ['Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Weekly']) + ['Python Weekly']) # When saved, John goes to 'other' review3.save() self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), - ['Python Monthly']) + ['Python Monthly']) self.assertEqual(list(Review.objects.using('other').filter(object_id=dive.pk).values_list('source', flat=True)), - ['Python Daily', 'Python Weekly']) + ['Python Daily', 'Python Weekly']) def test_generic_key_deletion(self): "Cascaded deletions of Generic Key relations issue queries on the right database" @@ -1360,18 +1360,18 @@ class RouterTestCase(TestCase): def test_generic_key_cross_database_protection(self): "Generic Key operations can span databases if they share a source" # Create a book and author on the default database - pro = Book.objects.using('default' - ).create(title="Pro Django", published=datetime.date(2008, 12, 16)) + pro = Book.objects.using( + 'default').create(title="Pro Django", published=datetime.date(2008, 12, 16)) - review1 = Review.objects.using('default' - ).create(source="Python Monthly", content_object=pro) + review1 = Review.objects.using( + 'default').create(source="Python Monthly", content_object=pro) # Create a book and author on the other database - dive = Book.objects.using('other' - ).create(title="Dive into Python", published=datetime.date(2009, 5, 4)) + dive = Book.objects.using( + 'other').create(title="Dive into Python", published=datetime.date(2009, 5, 4)) - review2 = Review.objects.using('other' - ).create(source="Python Weekly", content_object=dive) + review2 = Review.objects.using( + 'other').create(source="Python Weekly", content_object=dive) # Set a generic foreign key with an object from a different database try: @@ -1571,6 +1571,7 @@ class AuthTestCase(TestCase): command_output = new_io.getvalue().strip() self.assertTrue('"email": "alice@example.com"' in command_output) + class AntiPetRouter(object): # A router that only expresses an opinion on migrate, # passing pets to the 'other' database @@ -1582,6 +1583,7 @@ class AntiPetRouter(object): else: return model._meta.object_name != 'Pet' + class FixtureTestCase(TestCase): multi_db = True fixtures = ['multidb-common', 'multidb'] @@ -1604,7 +1606,8 @@ class FixtureTestCase(TestCase): except Book.DoesNotExist: self.fail('"Pro Django" should exist on default database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('other').get, title="Pro Django" ) @@ -1615,11 +1618,13 @@ class FixtureTestCase(TestCase): except Book.DoesNotExist: self.fail('"Dive into Python" should exist on other database') - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.get, title="Dive into Python" ) - self.assertRaises(Book.DoesNotExist, + self.assertRaises( + Book.DoesNotExist, Book.objects.using('default').get, title="Dive into Python" ) @@ -1640,6 +1645,7 @@ class FixtureTestCase(TestCase): # No objects will actually be loaded self.assertEqual(command_output, "Installed 0 object(s) (of 2) from 1 fixture(s)") + class PickleQuerySetTestCase(TestCase): multi_db = True @@ -1657,6 +1663,7 @@ class DatabaseReceiver(object): def __call__(self, signal, sender, **kwargs): self._database = kwargs['using'] + class WriteToOtherRouter(object): """ A router that sends all writes to the other database. @@ -1664,6 +1671,7 @@ class WriteToOtherRouter(object): def db_for_write(self, model, **hints): return "other" + class SignalTests(TestCase): multi_db = True @@ -1771,6 +1779,7 @@ class SignalTests(TestCase): self._write_to_default() self.assertEqual(receiver._database, "other") + class AttributeErrorRouter(object): "A router to test the exception handling of ConnectionRouter" def db_for_read(self, model, **hints): @@ -1779,6 +1788,7 @@ class AttributeErrorRouter(object): def db_for_write(self, model, **hints): raise AttributeError + class RouterAttributeErrorTestCase(TestCase): multi_db = True @@ -1824,12 +1834,14 @@ class RouterAttributeErrorTestCase(TestCase): router.routers = [AttributeErrorRouter()] # Install our router self.assertRaises(AttributeError, setattr, b, 'authors', [p]) + class ModelMetaRouter(object): "A router to ensure model arguments are real model classes" def db_for_write(self, model, **hints): if not hasattr(model, '_meta'): raise ValueError + class RouterModelArgumentTestCase(TestCase): multi_db = True -- cgit v1.3