Fix all violators of E231

This commit is contained in:
Alex Gaynor 2013-10-26 12:15:03 -07:00
parent f2d8027c9a
commit 9d740eb8b1
74 changed files with 628 additions and 629 deletions

View File

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

View File

@ -5,9 +5,9 @@ from django.core.management.base import BaseCommand
class Command(BaseCommand): class Command(BaseCommand):
option_list = BaseCommand.option_list + ( option_list = BaseCommand.option_list + (
make_option('--option_a','-a', action='store', dest='option_a', default='1'), make_option('--option_a', '-a', action='store', dest='option_a', default='1'),
make_option('--option_b','-b', action='store', dest='option_b', default='2'), make_option('--option_b', '-b', action='store', dest='option_b', default='2'),
make_option('--option_c','-c', action='store', dest='option_c', default='3'), make_option('--option_c', '-c', action='store', dest='option_c', default='3'),
) )
help = 'Test basic commands' help = 'Test basic commands'
requires_model_validation = False requires_model_validation = False

View File

@ -12,7 +12,7 @@ class MyFileField(models.FileField):
class Member(models.Model): class Member(models.Model):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
birthdate = models.DateTimeField(blank=True, null=True) birthdate = models.DateTimeField(blank=True, null=True)
gender = models.CharField(max_length=1, blank=True, choices=[('M','Male'), ('F', 'Female')]) gender = models.CharField(max_length=1, blank=True, choices=[('M', 'Male'), ('F', 'Female')])
email = models.EmailField(blank=True) email = models.EmailField(blank=True)
def __str__(self): def __str__(self):

View File

@ -101,7 +101,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
def testRadioFieldsForeignKey(self): def testRadioFieldsForeignKey(self):
ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect, ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect,
radio_fields={'main_band':admin.VERTICAL}) radio_fields={'main_band': admin.VERTICAL})
self.assertEqual(ff.empty_label, None) self.assertEqual(ff.empty_label, None)
def testManyToMany(self): def testManyToMany(self):
@ -126,7 +126,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
""" """
class BandAdmin(admin.ModelAdmin): class BandAdmin(admin.ModelAdmin):
formfield_overrides = { formfield_overrides = {
CharField: {'widget': forms.TextInput(attrs={'size':'10'})} CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
} }
ma = BandAdmin(models.Band, admin.site) ma = BandAdmin(models.Band, admin.site)
f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None) f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None)
@ -158,7 +158,7 @@ class AdminFormfieldForDBFieldTests(TestCase):
def testChoicesWithRadioFields(self): def testChoicesWithRadioFields(self):
self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect, self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
radio_fields={'gender':admin.VERTICAL}) radio_fields={'gender': admin.VERTICAL})
def testInheritance(self): def testInheritance(self):
self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget) self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)

View File

@ -196,7 +196,7 @@ class AggregationTests(TestCase):
"name": 'The Definitive Guide to Django: Web Development Done Right', "name": 'The Definitive Guide to Django: Web Development Done Right',
}) })
obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name','mean_auth_age').get(pk=1) obj = Book.objects.annotate(mean_auth_age=Avg('authors__age')).extra(select={'price_per_page' : 'price / pages'}).values('name', 'mean_auth_age').get(pk=1)
self.assertEqual(obj, { self.assertEqual(obj, {
'mean_auth_age': 34.5, 'mean_auth_age': 34.5,
'name': 'The Definitive Guide to Django: Web Development Done Right', 'name': 'The Definitive Guide to Django: Web Development Done Right',
@ -346,7 +346,7 @@ class AggregationTests(TestCase):
def test_aggregate_fexpr(self): def test_aggregate_fexpr(self):
# Aggregates can be used with F() expressions # Aggregates can be used with F() expressions
# ... where the F() is pushed into the HAVING clause # ... where the F() is pushed into the HAVING clause
qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_books__lt=F('num_awards')/2).order_by('name').values('name', 'num_books', 'num_awards')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9},
@ -355,7 +355,7 @@ class AggregationTests(TestCase):
lambda p: p, lambda p: p,
) )
qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name', 'num_books', 'num_awards')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'num_books': 2, 'name': 'Apress', 'num_awards': 3}, {'num_books': 2, 'name': 'Apress', 'num_awards': 3},
@ -366,7 +366,7 @@ class AggregationTests(TestCase):
) )
# ... and where the F() references an aggregate # ... and where the F() references an aggregate
qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name','num_books','num_awards') qs = Publisher.objects.annotate(num_books=Count('book')).filter(num_awards__gt=2*F('num_books')).order_by('name').values('name', 'num_books', 'num_awards')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9}, {'num_books': 1, 'name': 'Morgan Kaufmann', 'num_awards': 9},
@ -375,7 +375,7 @@ class AggregationTests(TestCase):
lambda p: p, lambda p: p,
) )
qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name','num_books','num_awards') qs = Publisher.objects.annotate(num_books=Count('book')).exclude(num_books__lt=F('num_awards')/2).order_by('name').values('name', 'num_books', 'num_awards')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'num_books': 2, 'name': 'Apress', 'num_awards': 3}, {'num_books': 2, 'name': 'Apress', 'num_awards': 3},
@ -456,7 +456,7 @@ class AggregationTests(TestCase):
# Regression for #10132 - If the values() clause only mentioned extra # Regression for #10132 - If the values() clause only mentioned extra
# (select=) columns, those columns are used for grouping # (select=) columns, those columns are used for grouping
qs = Book.objects.extra(select={'pub':'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub') qs = Book.objects.extra(select={'pub': 'publisher_id'}).values('pub').annotate(Count('id')).order_by('pub')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'pub': 1, 'id__count': 2}, {'pub': 1, 'id__count': 2},
@ -467,7 +467,7 @@ class AggregationTests(TestCase):
lambda b: b lambda b: b
) )
qs = Book.objects.extra(select={'pub':'publisher_id', 'foo':'pages'}).values('pub').annotate(Count('id')).order_by('pub') qs = Book.objects.extra(select={'pub': 'publisher_id', 'foo': 'pages'}).values('pub').annotate(Count('id')).order_by('pub')
self.assertQuerysetEqual( self.assertQuerysetEqual(
qs, [ qs, [
{'pub': 1, 'id__count': 2}, {'pub': 1, 'id__count': 2},

View File

@ -14,7 +14,7 @@ class Article(models.Model):
pub_date = models.DateTimeField() pub_date = models.DateTimeField()
class Meta: class Meta:
ordering = ('pub_date','headline') ordering = ('pub_date', 'headline')
def __str__(self): def __str__(self):
return self.headline return self.headline

48
tests/cache/tests.py vendored
View File

@ -682,55 +682,55 @@ class BaseCacheTests(object):
def test_cache_versioning_get_set_many(self): def test_cache_versioning_get_set_many(self):
# set, using default version = 1 # set, using default version = 1
self.cache.set_many({'ford1': 37, 'arthur1': 42}) self.cache.set_many({'ford1': 37, 'arthur1': 42})
self.assertEqual(self.cache.get_many(['ford1','arthur1']), self.assertEqual(self.cache.get_many(['ford1', 'arthur1']),
{'ford1': 37, 'arthur1': 42}) {'ford1': 37, 'arthur1': 42})
self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=1), self.assertEqual(self.cache.get_many(['ford1', 'arthur1'], version=1),
{'ford1': 37, 'arthur1': 42}) {'ford1': 37, 'arthur1': 42})
self.assertEqual(self.cache.get_many(['ford1','arthur1'], version=2), {}) self.assertEqual(self.cache.get_many(['ford1', 'arthur1'], version=2), {})
self.assertEqual(self.v2_cache.get_many(['ford1','arthur1']), {}) self.assertEqual(self.v2_cache.get_many(['ford1', 'arthur1']), {})
self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=1), self.assertEqual(self.v2_cache.get_many(['ford1', 'arthur1'], version=1),
{'ford1': 37, 'arthur1': 42}) {'ford1': 37, 'arthur1': 42})
self.assertEqual(self.v2_cache.get_many(['ford1','arthur1'], version=2), {}) self.assertEqual(self.v2_cache.get_many(['ford1', 'arthur1'], version=2), {})
# set, default version = 1, but manually override version = 2 # set, default version = 1, but manually override version = 2
self.cache.set_many({'ford2': 37, 'arthur2': 42}, version=2) self.cache.set_many({'ford2': 37, 'arthur2': 42}, version=2)
self.assertEqual(self.cache.get_many(['ford2','arthur2']), {}) self.assertEqual(self.cache.get_many(['ford2', 'arthur2']), {})
self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=1), {}) self.assertEqual(self.cache.get_many(['ford2', 'arthur2'], version=1), {})
self.assertEqual(self.cache.get_many(['ford2','arthur2'], version=2), self.assertEqual(self.cache.get_many(['ford2', 'arthur2'], version=2),
{'ford2': 37, 'arthur2': 42}) {'ford2': 37, 'arthur2': 42})
self.assertEqual(self.v2_cache.get_many(['ford2','arthur2']), self.assertEqual(self.v2_cache.get_many(['ford2', 'arthur2']),
{'ford2': 37, 'arthur2': 42}) {'ford2': 37, 'arthur2': 42})
self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=1), {}) self.assertEqual(self.v2_cache.get_many(['ford2', 'arthur2'], version=1), {})
self.assertEqual(self.v2_cache.get_many(['ford2','arthur2'], version=2), self.assertEqual(self.v2_cache.get_many(['ford2', 'arthur2'], version=2),
{'ford2': 37, 'arthur2': 42}) {'ford2': 37, 'arthur2': 42})
# v2 set, using default version = 2 # v2 set, using default version = 2
self.v2_cache.set_many({'ford3': 37, 'arthur3': 42}) self.v2_cache.set_many({'ford3': 37, 'arthur3': 42})
self.assertEqual(self.cache.get_many(['ford3','arthur3']), {}) self.assertEqual(self.cache.get_many(['ford3', 'arthur3']), {})
self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=1), {}) self.assertEqual(self.cache.get_many(['ford3', 'arthur3'], version=1), {})
self.assertEqual(self.cache.get_many(['ford3','arthur3'], version=2), self.assertEqual(self.cache.get_many(['ford3', 'arthur3'], version=2),
{'ford3': 37, 'arthur3': 42}) {'ford3': 37, 'arthur3': 42})
self.assertEqual(self.v2_cache.get_many(['ford3','arthur3']), self.assertEqual(self.v2_cache.get_many(['ford3', 'arthur3']),
{'ford3': 37, 'arthur3': 42}) {'ford3': 37, 'arthur3': 42})
self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=1), {}) self.assertEqual(self.v2_cache.get_many(['ford3', 'arthur3'], version=1), {})
self.assertEqual(self.v2_cache.get_many(['ford3','arthur3'], version=2), self.assertEqual(self.v2_cache.get_many(['ford3', 'arthur3'], version=2),
{'ford3': 37, 'arthur3': 42}) {'ford3': 37, 'arthur3': 42})
# v2 set, default version = 2, but manually override version = 1 # v2 set, default version = 2, but manually override version = 1
self.v2_cache.set_many({'ford4': 37, 'arthur4': 42}, version=1) self.v2_cache.set_many({'ford4': 37, 'arthur4': 42}, version=1)
self.assertEqual(self.cache.get_many(['ford4','arthur4']), self.assertEqual(self.cache.get_many(['ford4', 'arthur4']),
{'ford4': 37, 'arthur4': 42}) {'ford4': 37, 'arthur4': 42})
self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=1), self.assertEqual(self.cache.get_many(['ford4', 'arthur4'], version=1),
{'ford4': 37, 'arthur4': 42}) {'ford4': 37, 'arthur4': 42})
self.assertEqual(self.cache.get_many(['ford4','arthur4'], version=2), {}) self.assertEqual(self.cache.get_many(['ford4', 'arthur4'], version=2), {})
self.assertEqual(self.v2_cache.get_many(['ford4','arthur4']), {}) self.assertEqual(self.v2_cache.get_many(['ford4', 'arthur4']), {})
self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=1), self.assertEqual(self.v2_cache.get_many(['ford4', 'arthur4'], version=1),
{'ford4': 37, 'arthur4': 42}) {'ford4': 37, 'arthur4': 42})
self.assertEqual(self.v2_cache.get_many(['ford4','arthur4'], version=2), {}) self.assertEqual(self.v2_cache.get_many(['ford4', 'arthur4'], version=2), {})
def test_incr_version(self): def test_incr_version(self):
self.cache.set('answer', 42, version=2) self.cache.set('answer', 42, version=2)

View File

@ -115,7 +115,7 @@ class CsrfViewMiddlewareTest(TestCase):
self.assertEqual(csrf_cookie['secure'], True) self.assertEqual(csrf_cookie['secure'], True)
self.assertEqual(csrf_cookie['httponly'], True) self.assertEqual(csrf_cookie['httponly'], True)
self.assertEqual(csrf_cookie['path'], '/test/') self.assertEqual(csrf_cookie['path'], '/test/')
self.assertTrue('Cookie' in resp2.get('Vary','')) self.assertTrue('Cookie' in resp2.get('Vary', ''))
def test_process_response_get_token_not_used(self): def test_process_response_get_token_not_used(self):
""" """
@ -336,7 +336,7 @@ class CsrfViewMiddlewareTest(TestCase):
req = self._get_GET_no_csrf_cookie_request() req = self._get_GET_no_csrf_cookie_request()
resp = view(req) resp = view(req)
self.assertTrue(resp.cookies.get(settings.CSRF_COOKIE_NAME, False)) self.assertTrue(resp.cookies.get(settings.CSRF_COOKIE_NAME, False))
self.assertTrue('Cookie' in resp.get('Vary','')) self.assertTrue('Cookie' in resp.get('Vary', ''))
def test_ensures_csrf_cookie_with_middleware(self): def test_ensures_csrf_cookie_with_middleware(self):
""" """
@ -353,7 +353,7 @@ class CsrfViewMiddlewareTest(TestCase):
resp = view(req) resp = view(req)
resp2 = CsrfViewMiddleware().process_response(req, resp) resp2 = CsrfViewMiddleware().process_response(req, resp)
self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False)) self.assertTrue(resp2.cookies.get(settings.CSRF_COOKIE_NAME, False))
self.assertTrue('Cookie' in resp2.get('Vary','')) self.assertTrue('Cookie' in resp2.get('Vary', ''))
def test_ensures_csrf_cookie_no_logging(self): def test_ensures_csrf_cookie_no_logging(self):
""" """

View File

@ -31,7 +31,7 @@ class Author(models.Model):
class Meta: class Meta:
db_table = 'my_author_table' db_table = 'my_author_table'
ordering = ('last_name','first_name') ordering = ('last_name', 'first_name')
@python_2_unicode_compatible @python_2_unicode_compatible
class Article(models.Model): class Article(models.Model):

View File

@ -35,4 +35,4 @@ class Author(models.Model):
class Meta: class Meta:
db_table = 'my author table' db_table = 'my author table'
ordering = ('last_name','first_name') ordering = ('last_name', 'first_name')

View File

@ -50,7 +50,7 @@ full_decorator = compose(
# django.contrib.auth.decorators # django.contrib.auth.decorators
# Apply user_passes_test twice to check #9474 # Apply user_passes_test twice to check #9474
user_passes_test(lambda u:True), user_passes_test(lambda u: True),
login_required, login_required,
permission_required('change_world'), permission_required('change_world'),

View File

@ -369,7 +369,7 @@ class DefaultFiltersTests(TestCase):
'should be\nindented') 'should be\nindented')
self.assertEqual(wordwrap('this is a short paragraph of text.\n ' self.assertEqual(wordwrap('this is a short paragraph of text.\n '
'But this line should be indented',15), 'this is a short\n' 'But this line should be indented', 15), 'this is a short\n'
'paragraph of\ntext.\n But this line\nshould be\nindented') 'paragraph of\ntext.\n But this line\nshould be\nindented')
def test_rjust(self): def test_rjust(self):
@ -460,16 +460,16 @@ class DefaultFiltersTests(TestCase):
self.assertEqual(dictsortreversed(1, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '')
def test_first(self): def test_first(self):
self.assertEqual(first([0,1,2]), 0) self.assertEqual(first([0, 1, 2]), 0)
self.assertEqual(first(''), '') self.assertEqual(first(''), '')
self.assertEqual(first('test'), 't') self.assertEqual(first('test'), 't')
def test_join(self): def test_join(self):
self.assertEqual(join([0,1,2], 'glue'), '0glue1glue2') self.assertEqual(join([0, 1, 2], 'glue'), '0glue1glue2')
def test_length(self): def test_length(self):
self.assertEqual(length('1234'), 4) self.assertEqual(length('1234'), 4)
self.assertEqual(length([1,2,3,4]), 4) self.assertEqual(length([1, 2, 3, 4]), 4)
self.assertEqual(length_is([], 0), True) self.assertEqual(length_is([], 0), True)
self.assertEqual(length_is([], 1), False) self.assertEqual(length_is([], 1), False)
self.assertEqual(length_is('a', 1), True) self.assertEqual(length_is('a', 1), True)
@ -517,7 +517,7 @@ class DefaultFiltersTests(TestCase):
a = ULItem('a') a = ULItem('a')
b = ULItem('b') b = ULItem('b')
self.assertEqual(unordered_list([a,b]), self.assertEqual(unordered_list([a, b]),
'\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>') '\t<li>ulitem-a</li>\n\t<li>ulitem-b</li>')
# Old format for unordered lists should still work # Old format for unordered lists should still work
@ -623,7 +623,7 @@ class DefaultFiltersTests(TestCase):
self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), '1.0\xa0PB') self.assertEqual(filesizeformat(1024*1024*1024*1024*1024), '1.0\xa0PB')
self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000),
'2000.0\xa0PB') '2000.0\xa0PB')
self.assertEqual(filesizeformat(complex(1,-1)), '0\xa0bytes') self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0bytes')
self.assertEqual(filesizeformat(""), '0\xa0bytes') self.assertEqual(filesizeformat(""), '0\xa0bytes')
self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"),
'0\xa0bytes') '0\xa0bytes')
@ -634,14 +634,14 @@ class DefaultFiltersTests(TestCase):
self.assertEqual(pluralize(2), 's') self.assertEqual(pluralize(2), 's')
self.assertEqual(pluralize([1]), '') self.assertEqual(pluralize([1]), '')
self.assertEqual(pluralize([]), 's') self.assertEqual(pluralize([]), 's')
self.assertEqual(pluralize([1,2,3]), 's') self.assertEqual(pluralize([1, 2, 3]), 's')
self.assertEqual(pluralize(1,'es'), '') self.assertEqual(pluralize(1, 'es'), '')
self.assertEqual(pluralize(0,'es'), 'es') self.assertEqual(pluralize(0, 'es'), 'es')
self.assertEqual(pluralize(2,'es'), 'es') self.assertEqual(pluralize(2, 'es'), 'es')
self.assertEqual(pluralize(1,'y,ies'), 'y') self.assertEqual(pluralize(1, 'y,ies'), 'y')
self.assertEqual(pluralize(0,'y,ies'), 'ies') self.assertEqual(pluralize(0, 'y,ies'), 'ies')
self.assertEqual(pluralize(2,'y,ies'), 'ies') self.assertEqual(pluralize(2, 'y,ies'), 'ies')
self.assertEqual(pluralize(0,'y,ies,error'), '') self.assertEqual(pluralize(0, 'y,ies,error'), '')
def test_phone2numeric(self): def test_phone2numeric(self):
self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377') self.assertEqual(phone2numeric_filter('0800 flowers'), '0800 3569377')
@ -691,7 +691,7 @@ class DefaultFiltersI18NTests(TransRealMixin, TestCase):
'1,0\xa0PB') '1,0\xa0PB')
self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000), self.assertEqual(filesizeformat(1024*1024*1024*1024*1024*2000),
'2000,0\xa0PB') '2000,0\xa0PB')
self.assertEqual(filesizeformat(complex(1,-1)), '0\xa0Bytes') self.assertEqual(filesizeformat(complex(1, -1)), '0\xa0Bytes')
self.assertEqual(filesizeformat(""), '0\xa0Bytes') self.assertEqual(filesizeformat(""), '0\xa0Bytes')
self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"), self.assertEqual(filesizeformat("\N{GREEK SMALL LETTER ALPHA}"),
'0\xa0Bytes') '0\xa0Bytes')

View File

@ -303,7 +303,7 @@ class Ticket19102Tests(TestCase):
Login.objects.order_by('description').filter( Login.objects.order_by('description').filter(
orgunit__name__isnull=False orgunit__name__isnull=False
).extra( ).extra(
select={'extraf':'1'} select={'extraf': '1'}
).filter( ).filter(
pk=self.l1.pk pk=self.l1.pk
).delete() ).delete()

View File

@ -51,7 +51,7 @@ class DispatcherTests(unittest.TestCase):
def testExact(self): def testExact(self):
a_signal.connect(receiver_1_arg, sender=self) a_signal.connect(receiver_1_arg, sender=self)
expected = [(receiver_1_arg,"test")] expected = [(receiver_1_arg, "test")]
result = a_signal.send(sender=self, val="test") result = a_signal.send(sender=self, val="test")
self.assertEqual(result, expected) self.assertEqual(result, expected)
a_signal.disconnect(receiver_1_arg, sender=self) a_signal.disconnect(receiver_1_arg, sender=self)
@ -59,7 +59,7 @@ class DispatcherTests(unittest.TestCase):
def testIgnoredSender(self): def testIgnoredSender(self):
a_signal.connect(receiver_1_arg) a_signal.connect(receiver_1_arg)
expected = [(receiver_1_arg,"test")] expected = [(receiver_1_arg, "test")]
result = a_signal.send(sender=self, val="test") result = a_signal.send(sender=self, val="test")
self.assertEqual(result, expected) self.assertEqual(result, expected)
a_signal.disconnect(receiver_1_arg) a_signal.disconnect(receiver_1_arg)

View File

@ -63,7 +63,7 @@ class DistinctOnTests(TestCase):
['<Celebrity: c1>', '<Celebrity: c2>'], ['<Celebrity: c1>', '<Celebrity: c2>'],
), ),
( (
StaffTag.objects.distinct('staff','tag'), StaffTag.objects.distinct('staff', 'tag'),
['<StaffTag: t1 -> p1>'], ['<StaffTag: t1 -> p1>'],
), ),
( (

View File

@ -41,4 +41,4 @@ class TestObject(models.Model):
third = models.CharField(max_length=20) third = models.CharField(max_length=20)
def __str__(self): def __str__(self):
return 'TestObject: %s,%s,%s' % (self.first,self.second,self.third) return 'TestObject: %s,%s,%s' % (self.first, self.second, self.third)

View File

@ -180,100 +180,100 @@ class ExtraRegressTests(TestCase):
obj.save() obj.save()
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values()), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values()),
[{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}]
) )
# Extra clauses after an empty values clause are still included # Extra clauses after an empty values clause are still included
self.assertEqual( self.assertEqual(
list(TestObject.objects.values().extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), list(TestObject.objects.values().extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))),
[{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}] [{'bar': 'second', 'third': 'third', 'second': 'second', 'whiz': 'third', 'foo': 'first', 'id': obj.pk, 'first': 'first'}]
) )
# Extra columns are ignored if not mentioned in the values() clause # Extra columns are ignored if not mentioned in the values() clause
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('first', 'second')),
[{'second': 'second', 'first': 'first'}] [{'second': 'second', 'first': 'first'}]
) )
# Extra columns after a non-empty values() clause are ignored # Extra columns after a non-empty values() clause are ignored
self.assertEqual( self.assertEqual(
list(TestObject.objects.values('first', 'second').extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), list(TestObject.objects.values('first', 'second').extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))),
[{'second': 'second', 'first': 'first'}] [{'second': 'second', 'first': 'first'}]
) )
# Extra columns can be partially returned # Extra columns can be partially returned
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('first', 'second', 'foo')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('first', 'second', 'foo')),
[{'second': 'second', 'foo': 'first', 'first': 'first'}] [{'second': 'second', 'foo': 'first', 'first': 'first'}]
) )
# Also works if only extra columns are included # Also works if only extra columns are included
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values('foo', 'whiz')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values('foo', 'whiz')),
[{'foo': 'first', 'whiz': 'third'}] [{'foo': 'first', 'whiz': 'third'}]
) )
# Values list works the same way # Values list works the same way
# All columns are returned for an empty values_list() # All columns are returned for an empty values_list()
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list()), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list()),
[('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')]
) )
# Extra columns after an empty values_list() are still included # Extra columns after an empty values_list() are still included
self.assertEqual( self.assertEqual(
list(TestObject.objects.values_list().extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), list(TestObject.objects.values_list().extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))),
[('first', 'second', 'third', obj.pk, 'first', 'second', 'third')] [('first', 'second', 'third', obj.pk, 'first', 'second', 'third')]
) )
# Extra columns ignored completely if not mentioned in values_list() # Extra columns ignored completely if not mentioned in values_list()
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'second')),
[('first', 'second')] [('first', 'second')]
) )
# Extra columns after a non-empty values_list() clause are ignored completely # Extra columns after a non-empty values_list() clause are ignored completely
self.assertEqual( self.assertEqual(
list(TestObject.objects.values_list('first', 'second').extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third'))))), list(TestObject.objects.values_list('first', 'second').extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third'))))),
[('first', 'second')] [('first', 'second')]
) )
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('second', flat=True)), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('second', flat=True)),
['second'] ['second']
) )
# Only the extra columns specified in the values_list() are returned # Only the extra columns specified in the values_list() are returned
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first', 'second', 'whiz')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'second', 'whiz')),
[('first', 'second', 'third')] [('first', 'second', 'third')]
) )
# ...also works if only extra columns are included # ...also works if only extra columns are included
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('foo','whiz')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('foo', 'whiz')),
[('first', 'third')] [('first', 'third')]
) )
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', flat=True)), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', flat=True)),
['third'] ['third']
) )
# ... and values are returned in the order they are specified # ... and values are returned in the order they are specified
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz','foo')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', 'foo')),
[('third', 'first')] [('third', 'first')]
) )
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('first','id')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('first', 'id')),
[('first', obj.pk)] [('first', obj.pk)]
) )
self.assertEqual( self.assertEqual(
list(TestObject.objects.extra(select=OrderedDict((('foo','first'), ('bar','second'), ('whiz','third')))).values_list('whiz', 'first', 'bar', 'id')), list(TestObject.objects.extra(select=OrderedDict((('foo', 'first'), ('bar', 'second'), ('whiz', 'third')))).values_list('whiz', 'first', 'bar', 'id')),
[('third', 'first', 'second', obj.pk)] [('third', 'first', 'second', obj.pk)]
) )

View File

@ -403,7 +403,7 @@ class UnicodeFileNameTests(unittest.TestCase):
out the encoding situation between doctest and this file, but the actual out the encoding situation between doctest and this file, but the actual
repr doesn't matter; it just shouldn't return a unicode object. repr doesn't matter; it just shouldn't return a unicode object.
""" """
uf = UploadedFile(name='¿Cómo?',content_type='text') uf = UploadedFile(name='¿Cómo?', content_type='text')
self.assertEqual(type(uf.__repr__()), str) self.assertEqual(type(uf.__repr__()), str)
# Tests for a race condition on file saving (#4948). # Tests for a race condition on file saving (#4948).

View File

@ -80,7 +80,7 @@ class FileUploadTests(TestCase):
'Content-Disposition: form-data; name="file"; filename="test.txt"', 'Content-Disposition: form-data; name="file"; filename="test.txt"',
'Content-Type: application/octet-stream', 'Content-Type: application/octet-stream',
'Content-Transfer-Encoding: base64', 'Content-Transfer-Encoding: base64',
'',])) '']))
payload.write(b"\r\n" + base64.b64encode(force_bytes(content)) + b"\r\n") payload.write(b"\r\n" + base64.b64encode(force_bytes(content)) + b"\r\n")
payload.write('--' + client.BOUNDARY + '--\r\n') payload.write('--' + client.BOUNDARY + '--\r\n')
r = { r = {

View File

@ -17,7 +17,7 @@ class SampleTestCase(TestCase):
"Test cases can load fixture objects into models defined in packages" "Test cases can load fixture objects into models defined in packages"
self.assertEqual(Article.objects.count(), 3) self.assertEqual(Article.objects.count(), 3)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.all(),[ Article.objects.all(), [
"Django conquers world!", "Django conquers world!",
"Copyright is fine the way it is", "Copyright is fine the way it is",
"Poker has no place on ESPN", "Poker has no place on ESPN",

View File

@ -38,7 +38,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
# The forms library comes with some extra, higher-level Field and Widget # The forms library comes with some extra, higher-level Field and Widget
def test_selectdate(self): def test_selectdate(self):
w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016')) w = SelectDateWidget(years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'))
# Rendering the default state. # Rendering the default state.
self.assertHTMLEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> self.assertHTMLEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month">
@ -293,7 +293,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
</select>""") </select>""")
# Using a SelectDateWidget in a form. # Using a SelectDateWidget in a form.
w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) w = SelectDateWidget(years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'), required=False)
self.assertHTMLEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month"> self.assertHTMLEqual(w.render('mydate', ''), """<select name="mydate_month" id="id_mydate_month">
<option value="0">---</option> <option value="0">---</option>
<option value="1">January</option> <option value="1">January</option>
@ -419,7 +419,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
<option value="2016">2016</option> <option value="2016">2016</option>
</select>""") </select>""")
a = GetDate({'mydate_month':'4', 'mydate_day':'1', 'mydate_year':'2008'}) a = GetDate({'mydate_month': '4', 'mydate_day': '1', 'mydate_year': '2008'})
self.assertTrue(a.is_valid()) self.assertTrue(a.is_valid())
self.assertEqual(a.cleaned_data['mydate'], datetime.date(2008, 4, 1)) self.assertEqual(a.cleaned_data['mydate'], datetime.date(2008, 4, 1))
@ -429,17 +429,17 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
self.assertHTMLEqual(a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" />') self.assertHTMLEqual(a['mydate'].as_hidden(), '<input type="hidden" name="mydate" value="2008-4-1" id="id_mydate" />')
b = GetDate({'mydate':'2008-4-1'}) b = GetDate({'mydate': '2008-4-1'})
self.assertTrue(b.is_valid()) self.assertTrue(b.is_valid())
self.assertEqual(b.cleaned_data['mydate'], datetime.date(2008, 4, 1)) self.assertEqual(b.cleaned_data['mydate'], datetime.date(2008, 4, 1))
# Invalid dates shouldn't be allowed # Invalid dates shouldn't be allowed
c = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) c = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'})
self.assertFalse(c.is_valid()) self.assertFalse(c.is_valid())
self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']}) self.assertEqual(c.errors, {'mydate': ['Enter a valid date.']})
# label tag is correctly associated with month dropdown # label tag is correctly associated with month dropdown
d = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'}) d = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
self.assertTrue('<label for="id_mydate_month">' in d.as_p()) self.assertTrue('<label for="id_mydate_month">' in d.as_p())
def test_multiwidget(self): def test_multiwidget(self):
@ -488,31 +488,31 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
def compress(self, data_list): def compress(self, data_list):
if data_list: if data_list:
return '%s,%s,%s' % (data_list[0],''.join(data_list[1]),data_list[2]) return '%s,%s,%s' % (data_list[0], ''.join(data_list[1]), data_list[2])
return None return None
f = ComplexField(widget=w) f = ComplexField(widget=w)
self.assertEqual(f.clean(['some text', ['J','P'], ['2007-04-25','6:24:00']]), 'some text,JP,2007-04-25 06:24:00') self.assertEqual(f.clean(['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]), 'some text,JP,2007-04-25 06:24:00')
self.assertFormErrors(['Select a valid choice. X is not one of the available choices.'], f.clean, ['some text',['X'], ['2007-04-25','6:24:00']]) self.assertFormErrors(['Select a valid choice. X is not one of the available choices.'], f.clean, ['some text', ['X'], ['2007-04-25', '6:24:00']])
# If insufficient data is provided, None is substituted # If insufficient data is provided, None is substituted
self.assertFormErrors(['This field is required.'], f.clean, ['some text',['JP']]) self.assertFormErrors(['This field is required.'], f.clean, ['some text', ['JP']])
# test with no initial data # test with no initial data
self.assertTrue(f._has_changed(None, ['some text', ['J','P'], ['2007-04-25','6:24:00']])) self.assertTrue(f._has_changed(None, ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]))
# test when the data is the same as initial # test when the data is the same as initial
self.assertFalse(f._has_changed('some text,JP,2007-04-25 06:24:00', self.assertFalse(f._has_changed('some text,JP,2007-04-25 06:24:00',
['some text', ['J','P'], ['2007-04-25','6:24:00']])) ['some text', ['J', 'P'], ['2007-04-25', '6:24:00']]))
# test when the first widget's data has changed # test when the first widget's data has changed
self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00', self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00',
['other text', ['J','P'], ['2007-04-25','6:24:00']])) ['other text', ['J', 'P'], ['2007-04-25', '6:24:00']]))
# test when the last widget's data has changed. this ensures that it is not # test when the last widget's data has changed. this ensures that it is not
# short circuiting while testing the widgets. # short circuiting while testing the widgets.
self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00', self.assertTrue(f._has_changed('some text,JP,2007-04-25 06:24:00',
['some text', ['J','P'], ['2009-04-25','11:44:00']])) ['some text', ['J', 'P'], ['2009-04-25', '11:44:00']]))
class ComplexFieldForm(Form): class ComplexFieldForm(Form):
field1 = ComplexField(widget=w) field1 = ComplexField(widget=w)
@ -527,7 +527,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
</select> </select>
<input type="text" name="field1_2_0" id="id_field1_2_0" /><input type="text" name="field1_2_1" id="id_field1_2_1" /></td></tr>""") <input type="text" name="field1_2_0" id="id_field1_2_0" /><input type="text" name="field1_2_1" id="id_field1_2_1" /></td></tr>""")
f = ComplexFieldForm({'field1_0':'some text','field1_1':['J','P'], 'field1_2_0':'2007-04-25', 'field1_2_1':'06:24:00'}) f = ComplexFieldForm({'field1_0': 'some text', 'field1_1': ['J', 'P'], 'field1_2_0': '2007-04-25', 'field1_2_1': '06:24:00'})
self.assertHTMLEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" /> self.assertHTMLEqual(f.as_table(), """<tr><th><label for="id_field1_0">Field1:</label></th><td><input type="text" name="field1_0" value="some text" id="id_field1_0" />
<select multiple="multiple" name="field1_1" id="id_field1_1"> <select multiple="multiple" name="field1_1" id="id_field1_1">
<option value="J" selected="selected">John</option> <option value="J" selected="selected">John</option>
@ -785,7 +785,7 @@ class FormsExtraL10NTestCase(TestCase):
super(FormsExtraL10NTestCase, self).tearDown() super(FormsExtraL10NTestCase, self).tearDown()
def test_l10n(self): def test_l10n(self):
w = SelectDateWidget(years=('2007','2008','2009','2010','2011','2012','2013','2014','2015','2016'), required=False) w = SelectDateWidget(years=('2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'), required=False)
self.assertEqual(w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010') self.assertEqual(w.value_from_datadict({'date_year': '2010', 'date_month': '8', 'date_day': '13'}, {}, 'date'), '13-08-2010')
self.assertHTMLEqual(w.render('date', '13-08-2010'), """<select name="date_day" id="id_date_day"> self.assertHTMLEqual(w.render('date', '13-08-2010'), """<select name="date_day" id="id_date_day">
@ -911,12 +911,12 @@ class FormsExtraL10NTestCase(TestCase):
def test_l10n_invalid_date_in(self): def test_l10n_invalid_date_in(self):
# Invalid dates shouldn't be allowed # Invalid dates shouldn't be allowed
a = GetDate({'mydate_month':'2', 'mydate_day':'31', 'mydate_year':'2010'}) a = GetDate({'mydate_month': '2', 'mydate_day': '31', 'mydate_year': '2010'})
self.assertFalse(a.is_valid()) self.assertFalse(a.is_valid())
# 'Geef een geldige datum op.' = 'Enter a valid date.' # 'Geef een geldige datum op.' = 'Enter a valid date.'
self.assertEqual(a.errors, {'mydate': ['Geef een geldige datum op.']}) self.assertEqual(a.errors, {'mydate': ['Geef een geldige datum op.']})
def test_form_label_association(self): def test_form_label_association(self):
# label tag is correctly associated with first rendered dropdown # label tag is correctly associated with first rendered dropdown
a = GetDate({'mydate_month':'1', 'mydate_day':'1', 'mydate_year':'2010'}) a = GetDate({'mydate_month': '1', 'mydate_day': '1', 'mydate_year': '2010'})
self.assertTrue('<label for="id_mydate_day">' in a.as_p()) self.assertTrue('<label for="id_mydate_day">' in a.as_p())

View File

@ -905,7 +905,7 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John') self.assertRaisesMessage(ValidationError, "'Select a valid choice. John is not one of the available choices.'", f.clean, 'John')
def test_choicefield_4(self): def test_choicefield_4(self):
f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')])
self.assertEqual('1', f.clean(1)) self.assertEqual('1', f.clean(1))
self.assertEqual('1', f.clean('1')) self.assertEqual('1', f.clean('1'))
self.assertEqual('3', f.clean(3)) self.assertEqual('3', f.clean(3))
@ -1043,7 +1043,7 @@ class FieldsTests(SimpleTestCase):
self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3']) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 3 is not one of the available choices.'", f.clean, ['3'])
def test_multiplechoicefield_3(self): def test_multiplechoicefield_3(self):
f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')]) f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3', 'A'), ('4', 'B'))), ('5', 'Other')])
self.assertEqual(['1'], f.clean([1])) self.assertEqual(['1'], f.clean([1]))
self.assertEqual(['1'], f.clean(['1'])) self.assertEqual(['1'], f.clean(['1']))
self.assertEqual(['1', '5'], f.clean([1, 5])) self.assertEqual(['1', '5'], f.clean([1, 5]))
@ -1051,7 +1051,7 @@ class FieldsTests(SimpleTestCase):
self.assertEqual(['1', '5'], f.clean(['1', 5])) self.assertEqual(['1', '5'], f.clean(['1', 5]))
self.assertEqual(['1', '5'], f.clean(['1', '5'])) self.assertEqual(['1', '5'], f.clean(['1', '5']))
self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6']) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['6'])
self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1','6']) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 6 is not one of the available choices.'", f.clean, ['1', '6'])
def test_multiplechoicefield_changed(self): def test_multiplechoicefield_changed(self):
f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')]) f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two'), ('3', 'Three')])
@ -1084,8 +1084,8 @@ class FieldsTests(SimpleTestCase):
def test_typedmultiplechoicefield_4(self): def test_typedmultiplechoicefield_4(self):
f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int) f = TypedMultipleChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
self.assertEqual([1, -1], f.clean(['1','-1'])) self.assertEqual([1, -1], f.clean(['1', '-1']))
self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1','2']) self.assertRaisesMessage(ValidationError, "'Select a valid choice. 2 is not one of the available choices.'", f.clean, ['1', '2'])
def test_typedmultiplechoicefield_5(self): def test_typedmultiplechoicefield_5(self):
# Even more weirdness: if you have a valid choice but your coercion function # Even more weirdness: if you have a valid choice but your coercion function

View File

@ -1124,7 +1124,7 @@ class FormsTestCase(TestCase):
class UserRegistration(Form): class UserRegistration(Form):
username = CharField(max_length=10) username = CharField(max_length=10)
password = CharField(widget=PasswordInput) password = CharField(widget=PasswordInput)
options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')]) options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')])
# We need to define functions that get called later.) # We need to define functions that get called later.)
def initial_django(): def initial_django():
@ -1134,10 +1134,10 @@ class FormsTestCase(TestCase):
return 'stephane' return 'stephane'
def initial_options(): def initial_options():
return ['f','b'] return ['f', 'b']
def initial_other_options(): def initial_other_options():
return ['b','w'] return ['b', 'w']
# Here, we're not submitting any data, so the initial value will be displayed.) # Here, we're not submitting any data, so the initial value will be displayed.)
p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False) p = UserRegistration(initial={'username': initial_django, 'options': initial_options}, auto_id=False)
@ -1166,7 +1166,7 @@ class FormsTestCase(TestCase):
<option value="b">bar</option> <option value="b">bar</option>
<option value="w">whiz</option> <option value="w">whiz</option>
</select></li>""") </select></li>""")
p = UserRegistration({'username': 'foo', 'options':['f','b']}, initial={'username': initial_django}, auto_id=False) p = UserRegistration({'username': 'foo', 'options': ['f', 'b']}, initial={'username': initial_django}, auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li> self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="foo" maxlength="10" /></li>
<li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li> <li><ul class="errorlist"><li>This field is required.</li></ul>Password: <input type="password" name="password" /></li>
<li>Options: <select multiple="multiple" name="options"> <li>Options: <select multiple="multiple" name="options">
@ -1187,7 +1187,7 @@ class FormsTestCase(TestCase):
class UserRegistration(Form): class UserRegistration(Form):
username = CharField(max_length=10, initial=initial_django) username = CharField(max_length=10, initial=initial_django)
password = CharField(widget=PasswordInput) password = CharField(widget=PasswordInput)
options = MultipleChoiceField(choices=[('f','foo'),('b','bar'),('w','whiz')], initial=initial_other_options) options = MultipleChoiceField(choices=[('f', 'foo'), ('b', 'bar'), ('w', 'whiz')], initial=initial_other_options)
p = UserRegistration(auto_id=False) p = UserRegistration(auto_id=False)
self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li> self.assertHTMLEqual(p.as_ul(), """<li>Username: <input type="text" name="username" value="django" maxlength="10" /></li>
@ -1813,7 +1813,7 @@ class FormsTestCase(TestCase):
class ChoicesField(MultiValueField): class ChoicesField(MultiValueField):
def __init__(self, fields=(), *args, **kwargs): def __init__(self, fields=(), *args, **kwargs):
fields = (ChoiceField(label='Rank', fields = (ChoiceField(label='Rank',
choices=((1,1),(2,2))), choices=((1, 1), (2, 2))),
CharField(label='Name', max_length=10)) CharField(label='Name', max_length=10))
super(ChoicesField, self).__init__(fields=fields, *args, **kwargs) super(ChoicesField, self).__init__(fields=fields, *args, **kwargs)

View File

@ -1106,19 +1106,19 @@ ChoiceFormSet = formset_factory(Choice)
class FormsetAsFooTests(TestCase): class FormsetAsFooTests(TestCase):
def test_as_table(self): def test_as_table(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertHTMLEqual(formset.as_table(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> self.assertHTMLEqual(formset.as_table(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr> <tr><th>Choice:</th><td><input type="text" name="choices-0-choice" value="Calexico" /></td></tr>
<tr><th>Votes:</th><td><input type="number" name="choices-0-votes" value="100" /></td></tr>""") <tr><th>Votes:</th><td><input type="number" name="choices-0-votes" value="100" /></td></tr>""")
def test_as_p(self): def test_as_p(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertHTMLEqual(formset.as_p(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> self.assertHTMLEqual(formset.as_p(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p> <p>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></p>
<p>Votes: <input type="number" name="choices-0-votes" value="100" /></p>""") <p>Votes: <input type="number" name="choices-0-votes" value="100" /></p>""")
def test_as_ul(self): def test_as_ul(self):
formset = ChoiceFormSet(data, auto_id=False, prefix='choices') formset = ChoiceFormSet(data, auto_id=False, prefix='choices')
self.assertHTMLEqual(formset.as_ul(),"""<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" /> self.assertHTMLEqual(formset.as_ul(), """<input type="hidden" name="choices-TOTAL_FORMS" value="1" /><input type="hidden" name="choices-INITIAL_FORMS" value="0" /><input type="hidden" name="choices-MIN_NUM_FORMS" value="0" /><input type="hidden" name="choices-MAX_NUM_FORMS" value="0" />
<li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li> <li>Choice: <input type="text" name="choices-0-choice" value="Calexico" /></li>
<li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>""") <li>Votes: <input type="number" name="choices-0-votes" value="100" /></li>""")
@ -1188,8 +1188,8 @@ class TestEmptyFormSet(TestCase):
def test_empty_formset_is_valid(self): def test_empty_formset_is_valid(self):
"""Test that an empty formset still calls clean()""" """Test that an empty formset still calls clean()"""
EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate) EmptyFsetWontValidateFormset = formset_factory(FavoriteDrinkForm, extra=0, formset=EmptyFsetWontValidate)
formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'0'},prefix="form") formset = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '0'}, prefix="form")
formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS':'0', 'form-TOTAL_FORMS':'1', 'form-0-name':'bah'},prefix="form") formset2 = EmptyFsetWontValidateFormset(data={'form-INITIAL_FORMS': '0', 'form-TOTAL_FORMS': '1', 'form-0-name': 'bah'}, prefix="form")
self.assertFalse(formset.is_valid()) self.assertFalse(formset.is_valid())
self.assertFalse(formset2.is_valid()) self.assertFalse(formset2.is_valid())

View File

@ -24,7 +24,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
self.assertEqual(result, time(13,30,5)) self.assertEqual(result, time(13, 30, 5))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -32,7 +32,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid, but non-default format, get a parsed result # Parse a time in a valid, but non-default format, get a parsed result
result = f.clean('13:30') result = f.clean('13:30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -40,7 +40,7 @@ class LocalizedTimeTests(SimpleTestCase):
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
result = f.clean('13:30:05.000155') result = f.clean('13:30:05.000155')
self.assertEqual(result, time(13,30,5,155)) self.assertEqual(result, time(13, 30, 5, 155))
def test_localized_timeField(self): def test_localized_timeField(self):
"Localized TimeFields act as unlocalized widgets" "Localized TimeFields act as unlocalized widgets"
@ -50,7 +50,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -58,7 +58,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30') result = f.clean('13:30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -73,7 +73,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -81,7 +81,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30') result = f.clean('13.30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -96,7 +96,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -104,7 +104,7 @@ class LocalizedTimeTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30') result = f.clean('13.30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -121,7 +121,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
self.assertEqual(result, time(13,30,5)) self.assertEqual(result, time(13, 30, 5))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -129,7 +129,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid, but non-default format, get a parsed result # Parse a time in a valid, but non-default format, get a parsed result
result = f.clean('1:30 PM') result = f.clean('1:30 PM')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -143,7 +143,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -151,7 +151,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('01:30 PM') result = f.clean('01:30 PM')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -166,7 +166,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -174,7 +174,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30') result = f.clean('13.30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -189,7 +189,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30.05') result = f.clean('13.30.05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -197,7 +197,7 @@ class CustomTimeInputFormatsTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13.30') result = f.clean('13.30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -213,7 +213,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -221,7 +221,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid, but non-default format, get a parsed result # Parse a time in a valid, but non-default format, get a parsed result
result = f.clean('13:30') result = f.clean('13:30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -235,7 +235,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30:05') result = f.clean('13:30:05')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -243,7 +243,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('13:30') result = f.clean('13:30')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -257,7 +257,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -265,7 +265,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30 PM') result = f.clean('1:30 PM')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -279,7 +279,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30:05 PM') result = f.clean('1:30:05 PM')
self.assertEqual(result, time(13,30,5)) 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) text = f.widget._format_value(result)
@ -287,7 +287,7 @@ class SimpleTimeFormatTests(SimpleTestCase):
# Parse a time in a valid format, get a parsed result # Parse a time in a valid format, get a parsed result
result = f.clean('1:30 PM') result = f.clean('1:30 PM')
self.assertEqual(result, time(13,30,0)) self.assertEqual(result, time(13, 30, 0))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -309,11 +309,11 @@ class LocalizedDateTests(SimpleTestCase):
self.assertRaises(forms.ValidationError, f.clean, '21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
self.assertEqual(f.clean('2010-12-21'), date(2010,12,21)) self.assertEqual(f.clean('2010-12-21'), date(2010, 12, 21))
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -321,7 +321,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('21.12.10') result = f.clean('21.12.10')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -335,7 +335,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -343,7 +343,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.10') result = f.clean('21.12.10')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -359,7 +359,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -367,7 +367,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010') result = f.clean('12-21-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -383,7 +383,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -391,7 +391,7 @@ class LocalizedDateTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010') result = f.clean('12-21-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -408,7 +408,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -416,7 +416,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('21-12-2010') result = f.clean('21-12-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -430,7 +430,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -438,7 +438,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21-12-2010') result = f.clean('21-12-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -453,7 +453,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -461,7 +461,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010') result = f.clean('12-21-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -476,7 +476,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010') result = f.clean('12.21.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -484,7 +484,7 @@ class CustomDateInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010') result = f.clean('12-21-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -499,7 +499,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21') result = f.clean('2010-12-21')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -507,7 +507,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('12/21/2010') result = f.clean('12/21/2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -521,7 +521,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21') result = f.clean('2010-12-21')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -529,7 +529,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12/21/2010') result = f.clean('12/21/2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -543,7 +543,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -551,7 +551,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21-12-2010') result = f.clean('21-12-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -565,7 +565,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010') result = f.clean('21.12.2010')
self.assertEqual(result, date(2010,12,21)) 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) text = f.widget._format_value(result)
@ -573,7 +573,7 @@ class SimpleDateFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21-12-2010') result = f.clean('21-12-2010')
self.assertEqual(result, date(2010,12,21)) self.assertEqual(result, date(2010, 12, 21))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -595,11 +595,11 @@ class LocalizedDateTimeTests(SimpleTestCase):
self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010') self.assertRaises(forms.ValidationError, f.clean, '1:30:05 PM 21/12/2010')
# ISO formats are accepted, even if not specified in formats.py # ISO formats are accepted, even if not specified in formats.py
self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010,12,21,13,30,5)) self.assertEqual(f.clean('2010-12-21 13:30:05'), datetime(2010, 12, 21, 13, 30, 5))
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010 13:30:05') result = f.clean('21.12.2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -607,7 +607,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('21.12.2010 13:30') result = f.clean('21.12.2010 13:30')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -621,7 +621,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010 13:30:05') result = f.clean('21.12.2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -629,7 +629,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('21.12.2010 13:30') result = f.clean('21.12.2010 13:30')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -645,7 +645,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30.05 12.21.2010') result = f.clean('13.30.05 12.21.2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -653,7 +653,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30 12-21-2010') result = f.clean('13.30 12-21-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -669,7 +669,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30.05 12.21.2010') result = f.clean('13.30.05 12.21.2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -677,7 +677,7 @@ class LocalizedDateTimeTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('13.30 12-21-2010') result = f.clean('13.30 12-21-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -694,7 +694,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21/12/2010') result = f.clean('1:30:05 PM 21/12/2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# Check that the parsed result does a round trip # Check that the parsed result does a round trip
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -702,7 +702,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('1:30 PM 21-12-2010') result = f.clean('1:30 PM 21-12-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -716,7 +716,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21/12/2010') result = f.clean('1:30:05 PM 21/12/2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -724,7 +724,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30 PM 21-12-2010') result = f.clean('1:30 PM 21-12-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -739,7 +739,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010 13:30:05') result = f.clean('12.21.2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -747,7 +747,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010 13:30') result = f.clean('12-21-2010 13:30')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -762,7 +762,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12.21.2010 13:30:05') result = f.clean('12.21.2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -770,7 +770,7 @@ class CustomDateTimeInputFormatsTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12-21-2010 13:30') result = f.clean('12-21-2010 13:30')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -785,7 +785,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21 13:30:05') result = f.clean('2010-12-21 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -793,7 +793,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid, but non-default format, get a parsed result # Parse a date in a valid, but non-default format, get a parsed result
result = f.clean('12/21/2010 13:30:05') result = f.clean('12/21/2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -807,7 +807,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('2010-12-21 13:30:05') result = f.clean('2010-12-21 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -815,7 +815,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('12/21/2010 13:30:05') result = f.clean('12/21/2010 13:30:05')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30, 5))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -829,7 +829,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21.12.2010') result = f.clean('1:30:05 PM 21.12.2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -837,7 +837,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30 PM 21-12-2010') result = f.clean('1:30 PM 21-12-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)
@ -851,7 +851,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30:05 PM 21.12.2010') result = f.clean('1:30:05 PM 21.12.2010')
self.assertEqual(result, datetime(2010,12,21,13,30,5)) 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) text = f.widget._format_value(result)
@ -859,7 +859,7 @@ class SimpleDateTimeFormatTests(SimpleTestCase):
# Parse a date in a valid format, get a parsed result # Parse a date in a valid format, get a parsed result
result = f.clean('1:30 PM 21-12-2010') result = f.clean('1:30 PM 21-12-2010')
self.assertEqual(result, datetime(2010,12,21,13,30)) self.assertEqual(result, datetime(2010, 12, 21, 13, 30))
# Check that the parsed result does a round trip to default format # Check that the parsed result does a round trip to default format
text = f.widget._format_value(result) text = f.widget._format_value(result)

View File

@ -14,7 +14,7 @@ class FormsMediaTestCase(TestCase):
def test_construction(self): def test_construction(self):
# Check construction of media objects # Check construction of media objects
m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))
self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(m), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js1"></script>
@ -23,9 +23,9 @@ class FormsMediaTestCase(TestCase):
class Foo: class Foo:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
m3 = Media(Foo) m3 = Media(Foo)
self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(m3), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -52,9 +52,9 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
w1 = MyWidget1() w1 = MyWidget1()
self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w1.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -77,23 +77,23 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w1 = MyWidget1() w1 = MyWidget1()
w2 = MyWidget2() w2 = MyWidget2()
@ -158,9 +158,9 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget6(MyWidget1): class MyWidget6(MyWidget1):
def _media(self): def _media(self):
@ -185,9 +185,9 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget7(MyWidget1): class MyWidget7(MyWidget1):
pass pass
@ -203,9 +203,9 @@ class FormsMediaTestCase(TestCase):
class MyWidget8(MyWidget1): class MyWidget8(MyWidget1):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w8 = MyWidget8() w8 = MyWidget8()
self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w8.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -222,9 +222,9 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget4(TextInput): class MyWidget4(TextInput):
def _media(self): def _media(self):
@ -249,9 +249,9 @@ class FormsMediaTestCase(TestCase):
class Media: class Media:
extend = False extend = False
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w10 = MyWidget10() w10 = MyWidget10()
self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
@ -264,17 +264,17 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget11(MyWidget1): class MyWidget11(MyWidget1):
class Media: class Media:
extend = True extend = True
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w11 = MyWidget11() w11 = MyWidget11()
self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w11.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -290,17 +290,17 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget12(MyWidget1): class MyWidget12(MyWidget1):
class Media: class Media:
extend = ('css',) extend = ('css',)
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w12 = MyWidget12() w12 = MyWidget12()
self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w12.media), """<link href="http://media.example.com/media/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -318,11 +318,11 @@ class FormsMediaTestCase(TestCase):
class MultimediaWidget(TextInput): class MultimediaWidget(TextInput):
class Media: class Media:
css = { css = {
'screen, print': ('/file1','/file2'), 'screen, print': ('/file1', '/file2'),
'screen': ('/file3',), 'screen': ('/file3',),
'print': ('/file4',) 'print': ('/file4',)
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
multimedia = MultimediaWidget() multimedia = MultimediaWidget()
self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
@ -340,23 +340,23 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
# MultiWidgets have a default media definition that gets all the # MultiWidgets have a default media definition that gets all the
# media from the component widgets # media from the component widgets
@ -382,23 +382,23 @@ class FormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
# You can ask a form for the media required by its widgets. # You can ask a form for the media required by its widgets.
class MyForm(Form): class MyForm(Form):
@ -466,7 +466,7 @@ class StaticFormsMediaTestCase(TestCase):
def test_construction(self): def test_construction(self):
# Check construction of media objects # Check construction of media objects
m = Media(css={'all': ('path/to/css1','/path/to/css2')}, js=('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3')) m = Media(css={'all': ('path/to/css1', '/path/to/css2')}, js=('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3'))
self.assertEqual(str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(m), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
<link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" /> <link href="/path/to/css2" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/path/to/js1"></script> <script type="text/javascript" src="/path/to/js1"></script>
@ -475,9 +475,9 @@ class StaticFormsMediaTestCase(TestCase):
class Foo: class Foo:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
m3 = Media(Foo) m3 = Media(Foo)
self.assertEqual(str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(m3), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -504,9 +504,9 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
w1 = MyWidget1() w1 = MyWidget1()
self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w1.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -529,23 +529,23 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w1 = MyWidget1() w1 = MyWidget1()
w2 = MyWidget2() w2 = MyWidget2()
@ -610,9 +610,9 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget6(MyWidget1): class MyWidget6(MyWidget1):
def _media(self): def _media(self):
@ -637,9 +637,9 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget7(MyWidget1): class MyWidget7(MyWidget1):
pass pass
@ -655,9 +655,9 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget8(MyWidget1): class MyWidget8(MyWidget1):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w8 = MyWidget8() w8 = MyWidget8()
self.assertEqual(str(w8.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w8.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -674,9 +674,9 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget4(TextInput): class MyWidget4(TextInput):
def _media(self): def _media(self):
@ -701,9 +701,9 @@ class StaticFormsMediaTestCase(TestCase):
class Media: class Media:
extend = False extend = False
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w10 = MyWidget10() w10 = MyWidget10()
self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w10.media), """<link href="/path/to/css3" type="text/css" media="all" rel="stylesheet" />
@ -716,17 +716,17 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget11(MyWidget1): class MyWidget11(MyWidget1):
class Media: class Media:
extend = True extend = True
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w11 = MyWidget11() w11 = MyWidget11()
self.assertEqual(str(w11.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w11.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -742,17 +742,17 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget12(MyWidget1): class MyWidget12(MyWidget1):
class Media: class Media:
extend = ('css',) extend = ('css',)
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
w12 = MyWidget12() w12 = MyWidget12()
self.assertEqual(str(w12.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" /> self.assertEqual(str(w12.media), """<link href="http://media.example.com/static/path/to/css1" type="text/css" media="all" rel="stylesheet" />
@ -770,11 +770,11 @@ class StaticFormsMediaTestCase(TestCase):
class MultimediaWidget(TextInput): class MultimediaWidget(TextInput):
class Media: class Media:
css = { css = {
'screen, print': ('/file1','/file2'), 'screen, print': ('/file1', '/file2'),
'screen': ('/file3',), 'screen': ('/file3',),
'print': ('/file4',) 'print': ('/file4',)
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
multimedia = MultimediaWidget() multimedia = MultimediaWidget()
self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" /> self.assertEqual(str(multimedia.media), """<link href="/file4" type="text/css" media="print" rel="stylesheet" />
@ -792,23 +792,23 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
# MultiWidgets have a default media definition that gets all the # MultiWidgets have a default media definition that gets all the
# media from the component widgets # media from the component widgets
@ -834,23 +834,23 @@ class StaticFormsMediaTestCase(TestCase):
class MyWidget1(TextInput): class MyWidget1(TextInput):
class Media: class Media:
css = { css = {
'all': ('path/to/css1','/path/to/css2') 'all': ('path/to/css1', '/path/to/css2')
} }
js = ('/path/to/js1','http://media.other.com/path/to/js2','https://secure.other.com/path/to/js3') js = ('/path/to/js1', 'http://media.other.com/path/to/js2', 'https://secure.other.com/path/to/js3')
class MyWidget2(TextInput): class MyWidget2(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css2','/path/to/css3') 'all': ('/path/to/css2', '/path/to/css3')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
class MyWidget3(TextInput): class MyWidget3(TextInput):
class Media: class Media:
css = { css = {
'all': ('/path/to/css3','path/to/css1') 'all': ('/path/to/css3', 'path/to/css1')
} }
js = ('/path/to/js1','/path/to/js4') js = ('/path/to/js1', '/path/to/js4')
# You can ask a form for the media required by its widgets. # You can ask a form for the media required by its widgets.
class MyForm(Form): class MyForm(Form):

View File

@ -15,7 +15,6 @@ from django.forms import (
Textarea, TextInput, TimeInput, Textarea, TextInput, TimeInput,
) )
from django.forms.widgets import RadioFieldRenderer from django.forms.widgets import RadioFieldRenderer
from django.utils import formats
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.utils import six from django.utils import six
from django.utils.translation import activate, deactivate, override from django.utils.translation import activate, deactivate, override
@ -691,7 +690,7 @@ beatle J R Ringo False""")
self.assertHTMLEqual(six.text_type(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), '<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>') self.assertHTMLEqual(six.text_type(w.render('email', 'ŠĐĆŽćžšđ', choices=[('ŠĐĆŽćžšđ', 'ŠĐabcĆŽćžšđ'), ('ćžšđ', 'abcćžšđ')])), '<ul>\n<li><label><input checked="checked" type="radio" name="email" value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" /> \u0160\u0110abc\u0106\u017d\u0107\u017e\u0161\u0111</label></li>\n<li><label><input type="radio" name="email" value="\u0107\u017e\u0161\u0111" /> abc\u0107\u017e\u0161\u0111</label></li>\n</ul>')
# Attributes provided at instantiation are passed to the constituent inputs # Attributes provided at instantiation are passed to the constituent inputs
w = RadioSelect(attrs={'id':'foo'}) w = RadioSelect(attrs={'id': 'foo'})
self.assertHTMLEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul id="foo"> self.assertHTMLEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo'))), """<ul id="foo">
<li><label for="foo_0"><input checked="checked" type="radio" id="foo_0" value="J" name="beatle" /> John</label></li> <li><label for="foo_0"><input checked="checked" type="radio" id="foo_0" value="J" name="beatle" /> John</label></li>
<li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li> <li><label for="foo_1"><input type="radio" id="foo_1" value="P" name="beatle" /> Paul</label></li>
@ -701,7 +700,7 @@ beatle J R Ringo False""")
# Attributes provided at render-time are passed to the constituent inputs # Attributes provided at render-time are passed to the constituent inputs
w = RadioSelect() w = RadioSelect()
self.assertHTMLEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id':'bar'}), """<ul id="bar"> self.assertHTMLEqual(w.render('beatle', 'J', choices=(('J', 'John'), ('P', 'Paul'), ('G', 'George'), ('R', 'Ringo')), attrs={'id': 'bar'}), """<ul id="bar">
<li><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></li> <li><label for="bar_0"><input checked="checked" type="radio" id="bar_0" value="J" name="beatle" /> John</label></li>
<li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li> <li><label for="bar_1"><input type="radio" id="bar_1" value="P" name="beatle" /> Paul</label></li>
<li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li> <li><label for="bar_2"><input type="radio" id="bar_2" value="G" name="beatle" /> George</label></li>
@ -716,7 +715,7 @@ beatle J R Ringo False""")
('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))),
('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))),
) )
self.assertHTMLEqual(w.render('nestchoice', 'dvd', attrs={'id':'media'}), """<ul id="media"> self.assertHTMLEqual(w.render('nestchoice', 'dvd', attrs={'id': 'media'}), """<ul id="media">
<li><label for="media_0"><input id="media_0" name="nestchoice" type="radio" value="unknown" /> Unknown</label></li> <li><label for="media_0"><input id="media_0" name="nestchoice" type="radio" value="unknown" /> Unknown</label></li>
<li>Audio<ul id="media_1"> <li>Audio<ul id="media_1">
<li><label for="media_1_0"><input id="media_1_0" name="nestchoice" type="radio" value="vinyl" /> Vinyl</label></li> <li><label for="media_1_0"><input id="media_1_0" name="nestchoice" type="radio" value="vinyl" /> Vinyl</label></li>
@ -735,7 +734,7 @@ beatle J R Ringo False""")
('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))), ('Audio', (('vinyl', 'Vinyl'), ('cd', 'CD'))),
('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))), ('Video', (('vhs', 'VHS'), ('dvd', 'DVD'))),
) )
self.assertHTMLEqual(w.render('nestchoice', ('vinyl', 'dvd'), attrs={'id':'media'}), """<ul id="media"> self.assertHTMLEqual(w.render('nestchoice', ('vinyl', 'dvd'), attrs={'id': 'media'}), """<ul id="media">
<li><label for="media_0"><input id="media_0" name="nestchoice" type="checkbox" value="unknown" /> Unknown</label></li> <li><label for="media_0"><input id="media_0" name="nestchoice" type="checkbox" value="unknown" /> Unknown</label></li>
<li>Audio<ul id="media_1"> <li>Audio<ul id="media_1">
<li><label for="media_1_0"><input checked="checked" id="media_1_0" name="nestchoice" type="checkbox" value="vinyl" /> Vinyl</label></li> <li><label for="media_1_0"><input checked="checked" id="media_1_0" name="nestchoice" type="checkbox" value="vinyl" /> Vinyl</label></li>
@ -912,7 +911,7 @@ beatle J R Ringo False""")
w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'}))) w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})))
self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
self.assertHTMLEqual(w.render('name', 'john__lennon'), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />') self.assertHTMLEqual(w.render('name', 'john__lennon'), '<input type="text" class="big" value="john" name="name_0" /><br /><input type="text" class="small" value="lennon" name="name_1" />')
self.assertHTMLEqual(w.render('name', 'john__lennon', attrs={'id':'foo'}), '<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />') self.assertHTMLEqual(w.render('name', 'john__lennon', attrs={'id': 'foo'}), '<input id="foo_0" type="text" class="big" value="john" name="name_0" /><br /><input id="foo_1" type="text" class="small" value="lennon" name="name_1" />')
w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'}) w = MyMultiWidget(widgets=(TextInput(attrs={'class': 'big'}), TextInput(attrs={'class': 'small'})), attrs={'id': 'bar'})
self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />') self.assertHTMLEqual(w.render('name', ['john', 'lennon']), '<input id="bar_0" type="text" class="big" value="john" name="name_0" /><br /><input id="bar_1" type="text" class="small" value="lennon" name="name_1" />')
@ -1081,12 +1080,12 @@ class SelectAndTextWidget(MultiWidget):
class WidgetTests(TestCase): class WidgetTests(TestCase):
def test_12048(self): def test_12048(self):
# See ticket #12048. # See ticket #12048.
w1 = SelectAndTextWidget(choices=[1,2,3]) w1 = SelectAndTextWidget(choices=[1, 2, 3])
w2 = copy.deepcopy(w1) w2 = copy.deepcopy(w1)
w2.choices = [4,5,6] w2.choices = [4, 5, 6]
# w2 ought to be independent of w1, since MultiWidget ought # w2 ought to be independent of w1, since MultiWidget ought
# to make a copy of its sub-widgets when it is copied. # to make a copy of its sub-widgets when it is copied.
self.assertEqual(w1.choices, [1,2,3]) self.assertEqual(w1.choices, [1, 2, 3])
def test_13390(self): def test_13390(self):
# See ticket #13390 # See ticket #13390

View File

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

View File

@ -291,7 +291,7 @@ class MonthArchiveViewTests(TestCase):
"Content can exist on any day of the previous month. Refs #14711" "Content can exist on any day of the previous month. Refs #14711"
self.pubdate_list = [ self.pubdate_list = [
datetime.date(2010, month, day) datetime.date(2010, month, day)
for month,day in ((9,1), (10,2), (11,3)) for month, day in ((9, 1), (10, 2), (11, 3))
] ]
for pubdate in self.pubdate_list: for pubdate in self.pubdate_list:
name = str(pubdate) name = str(pubdate)
@ -299,15 +299,15 @@ class MonthArchiveViewTests(TestCase):
res = self.client.get('/dates/books/2010/nov/allow_empty/') res = self.client.get('/dates/books/2010/nov/allow_empty/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['previous_month'], datetime.date(2010,10,1)) self.assertEqual(res.context['previous_month'], datetime.date(2010, 10, 1))
# The following test demonstrates the bug # The following test demonstrates the bug
res = self.client.get('/dates/books/2010/nov/') res = self.client.get('/dates/books/2010/nov/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['previous_month'], datetime.date(2010,10,1)) self.assertEqual(res.context['previous_month'], datetime.date(2010, 10, 1))
# The bug does not occur here because a Book with pubdate of Sep 1 exists # The bug does not occur here because a Book with pubdate of Sep 1 exists
res = self.client.get('/dates/books/2010/oct/') res = self.client.get('/dates/books/2010/oct/')
self.assertEqual(res.status_code, 200) self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['previous_month'], datetime.date(2010,9,1)) self.assertEqual(res.context['previous_month'], datetime.date(2010, 9, 1))
def test_datetime_month_view(self): def test_datetime_month_view(self):
BookSigning.objects.create(event_date=datetime.datetime(2008, 2, 1, 12, 0)) BookSigning.objects.create(event_date=datetime.datetime(2008, 2, 1, 12, 0))

View File

@ -113,7 +113,7 @@ class SpecializedAuthorCreate(generic.CreateView):
context_object_name = 'thingy' context_object_name = 'thingy'
def get_success_url(self): def get_success_url(self):
return reverse('author_detail', args=[self.object.id,]) return reverse('author_detail', args=[self.object.id])
class AuthorCreateRestricted(AuthorCreate): class AuthorCreateRestricted(AuthorCreate):
@ -151,7 +151,7 @@ class SpecializedAuthorUpdate(generic.UpdateView):
context_object_name = 'thingy' context_object_name = 'thingy'
def get_success_url(self): def get_success_url(self):
return reverse('author_detail', args=[self.object.id,]) return reverse('author_detail', args=[self.object.id])
class NaiveAuthorDelete(generic.DeleteView): class NaiveAuthorDelete(generic.DeleteView):
@ -205,7 +205,7 @@ class AuthorGetQuerySetFormView(generic.edit.ModelFormMixin):
class BookDetailGetObjectCustomQueryset(BookDetail): class BookDetailGetObjectCustomQueryset(BookDetail):
def get_object(self, queryset=None): def get_object(self, queryset=None):
return super(BookDetailGetObjectCustomQueryset,self).get_object( return super(BookDetailGetObjectCustomQueryset, self).get_object(
queryset=Book.objects.filter(pk=2)) queryset=Book.objects.filter(pk=2))

View File

@ -51,7 +51,7 @@ class ExtractorTests(SimpleTestCase):
q = "'" q = "'"
needle = 'msgid %s' % msgid needle = 'msgid %s' % msgid
msgid = re.escape(msgid) msgid = re.escape(msgid)
return self.assertTrue(re.search('^msgid %s' % msgid, s, re.MULTILINE), 'Could not find %(q)s%(n)s%(q)s in generated PO file' % {'n':needle, 'q':q}) return self.assertTrue(re.search('^msgid %s' % msgid, s, re.MULTILINE), 'Could not find %(q)s%(n)s%(q)s in generated PO file' % {'n': needle, 'q': q})
def assertNotMsgId(self, msgid, s, use_quotes=True): def assertNotMsgId(self, msgid, s, use_quotes=True):
if use_quotes: if use_quotes:
@ -474,7 +474,7 @@ class MultipleLocaleExtractionTests(ExtractorTests):
def test_multiple_locales(self): def test_multiple_locales(self):
os.chdir(self.test_dir) os.chdir(self.test_dir)
management.call_command('makemessages', locale=['pt','de'], verbosity=0) management.call_command('makemessages', locale=['pt', 'de'], verbosity=0)
self.assertTrue(os.path.exists(self.PO_FILE_PT)) self.assertTrue(os.path.exists(self.PO_FILE_PT))
self.assertTrue(os.path.exists(self.PO_FILE_DE)) self.assertTrue(os.path.exists(self.PO_FILE_DE))

View File

@ -9,7 +9,7 @@ class TestModel(models.Model):
class Company(models.Model): class Company(models.Model):
name = models.CharField(max_length=50) name = models.CharField(max_length=50)
date_added = models.DateTimeField(default=datetime(1799,1,31,23,59,59,0)) date_added = models.DateTimeField(default=datetime(1799, 1, 31, 23, 59, 59, 0))
cents_paid = models.DecimalField(max_digits=4, decimal_places=2) cents_paid = models.DecimalField(max_digits=4, decimal_places=2)
products_delivered = models.IntegerField() products_delivered = models.IntegerField()

View File

@ -303,7 +303,7 @@ class URLTagTests(URLTestCaseBase):
['/vertaald/', '/traduzidos/']) ['/vertaald/', '/traduzidos/'])
def test_context(self): def test_context(self):
ctx = Context({'lang1':'nl', 'lang2':'pt-br'}) ctx = Context({'lang1': 'nl', 'lang2': 'pt-br'})
tpl = Template("""{% load i18n %} tpl = Template("""{% load i18n %}
{% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %} {% language lang1 %}{% url 'no-prefix-translated' %}{% endlanguage %}
{% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""") {% language lang2 %}{% url 'no-prefix-translated' %}{% endlanguage %}""")

View File

@ -21,7 +21,7 @@ class InspectDBTestCase(TestCase):
# Lets limit the introspection to tables created for models of this # Lets limit the introspection to tables created for models of this
# application # application
call_command('inspectdb', call_command('inspectdb',
table_name_filter=lambda tn:tn.startswith('inspectdb_'), table_name_filter=lambda tn: tn.startswith('inspectdb_'),
stdout=out) stdout=out)
error_message = "inspectdb has examined a table that should have been filtered out." error_message = "inspectdb has examined a table that should have been filtered out."
# contrib.contenttypes is one of the apps always installed when running # contrib.contenttypes is one of the apps always installed when running
@ -100,7 +100,7 @@ class InspectDBTestCase(TestCase):
# Lets limit the introspection to tables created for models of this # Lets limit the introspection to tables created for models of this
# application # application
call_command('inspectdb', call_command('inspectdb',
table_name_filter=lambda tn:tn.startswith('inspectdb_'), table_name_filter=lambda tn: tn.startswith('inspectdb_'),
stdout=out) stdout=out)
output = out.getvalue() output = out.getvalue()
error_message = "inspectdb generated an attribute name which is a python keyword" error_message = "inspectdb generated an attribute name which is a python keyword"
@ -121,7 +121,7 @@ class InspectDBTestCase(TestCase):
# Lets limit the introspection to tables created for models of this # Lets limit the introspection to tables created for models of this
# application # application
call_command('inspectdb', call_command('inspectdb',
table_name_filter=lambda tn:tn.startswith('inspectdb_'), table_name_filter=lambda tn: tn.startswith('inspectdb_'),
stdout=out) stdout=out)
output = out.getvalue() output = out.getvalue()
error_message = "inspectdb generated a model field name which is a number" error_message = "inspectdb generated a model field name which is a number"
@ -159,7 +159,7 @@ class InspectDBTestCase(TestCase):
"""Test that by default the command generates models with `Meta.managed = False` (#14305)""" """Test that by default the command generates models with `Meta.managed = False` (#14305)"""
out = StringIO() out = StringIO()
call_command('inspectdb', call_command('inspectdb',
table_name_filter=lambda tn:tn.startswith('inspectdb_columntypes'), table_name_filter=lambda tn: tn.startswith('inspectdb_columntypes'),
stdout=out) stdout=out)
output = out.getvalue() output = out.getvalue()
self.longMessage = False self.longMessage = False

View File

@ -125,7 +125,7 @@ class LookupTests(TestCase):
def test_values(self): def test_values(self):
# values() returns a list of dictionaries instead of object instances -- # values() returns a list of dictionaries instead of object instances --
# and you can specify which fields you want to retrieve. # and you can specify which fields you want to retrieve.
identity = lambda x:x identity = lambda x: x
self.assertQuerysetEqual(Article.objects.values('headline'), self.assertQuerysetEqual(Article.objects.values('headline'),
[ [
{'headline': 'Article 5'}, {'headline': 'Article 5'},
@ -256,7 +256,7 @@ class LookupTests(TestCase):
# returned as a list of tuples, rather than a list of dictionaries. # returned as a list of tuples, rather than a list of dictionaries.
# Within each tuple, the order of the elements is the same as the order # Within each tuple, the order of the elements is the same as the order
# of fields in the values_list() call. # of fields in the values_list() call.
identity = lambda x:x identity = lambda x: x
self.assertQuerysetEqual(Article.objects.values_list('headline'), self.assertQuerysetEqual(Article.objects.values_list('headline'),
[ [
('Article 5',), ('Article 5',),

View File

@ -19,7 +19,7 @@ class RecursiveM2MTests(TestCase):
a.friends.add(b, c) a.friends.add(b, c)
# David is friends with Anne and Chuck - add in reverse direction # David is friends with Anne and Chuck - add in reverse direction
d.friends.add(a,c) d.friends.add(a, c)
# Who is friends with Anne? # Who is friends with Anne?
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -251,7 +251,7 @@ class ManyToManySignalsTest(TestCase):
self.assertEqual(self.m2m_changed_messages, expected_messages) self.assertEqual(self.m2m_changed_messages, expected_messages)
# direct assignment clears the set first, then adds # direct assignment clears the set first, then adds
self.vw.default_parts = [self.wheelset,self.doors,self.engine] self.vw.default_parts = [self.wheelset, self.doors, self.engine]
expected_messages.append({ expected_messages.append({
'instance': self.vw, 'instance': self.vw,
'action': 'pre_clear', 'action': 'pre_clear',
@ -397,7 +397,7 @@ class ManyToManySignalsTest(TestCase):
}) })
self.assertEqual(self.m2m_changed_messages, expected_messages) self.assertEqual(self.m2m_changed_messages, expected_messages)
self.chuck.idols = [self.alice,self.bob] self.chuck.idols = [self.alice, self.bob]
expected_messages.append({ expected_messages.append({
'instance': self.chuck, 'instance': self.chuck,
'action': 'pre_clear', 'action': 'pre_clear',

View File

@ -101,7 +101,7 @@ class M2mThroughTests(TestCase):
m2.save() m2.save()
# Verifying that those instances were re-saved successfully. # Verifying that those instances were re-saved successfully.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.rock.members.all(),[ self.rock.members.all(), [
'Jane', 'Jane',
'Jim' 'Jim'
], ],
@ -142,7 +142,7 @@ class M2mThroughTests(TestCase):
m2.save() m2.save()
# Verifying that those instances were re-saved successfully. # Verifying that those instances were re-saved successfully.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.jim.group_set.all(),[ self.jim.group_set.all(), [
'Rock', 'Rock',
'Roll' 'Roll'
], ],
@ -166,7 +166,7 @@ class M2mThroughTests(TestCase):
# If we get the number of people in Rock, it should be both Bob and Jim. # If we get the number of people in Rock, it should be both Bob and Jim.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.rock.custom_members.all(),[ self.rock.custom_members.all(), [
'Bob', 'Bob',
'Jim' 'Jim'
], ],
@ -174,14 +174,14 @@ class M2mThroughTests(TestCase):
) )
# Bob should only be in one custom group. # Bob should only be in one custom group.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.bob.custom.all(),[ self.bob.custom.all(), [
'Rock' 'Rock'
], ],
attrgetter("name") attrgetter("name")
) )
# Let's make sure our new descriptors don't conflict with the FK related_name. # Let's make sure our new descriptors don't conflict with the FK related_name.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.bob.custom_person_related_name.all(),[ self.bob.custom_person_related_name.all(), [
'<CustomMembership: Bob is a member of Rock>' '<CustomMembership: Bob is a member of Rock>'
] ]
) )
@ -199,7 +199,7 @@ class M2mThroughTests(TestCase):
# Tony should now show that Chris is his friend. # Tony should now show that Chris is his friend.
self.assertQuerysetEqual( self.assertQuerysetEqual(
tony.friends.all(),[ tony.friends.all(), [
'Chris' 'Chris'
], ],
attrgetter("name") attrgetter("name")
@ -214,7 +214,7 @@ class M2mThroughTests(TestCase):
# Having added Chris as a friend, let's make sure that his friend set reflects # Having added Chris as a friend, let's make sure that his friend set reflects
# that addition. # that addition.
self.assertQuerysetEqual( self.assertQuerysetEqual(
chris.friends.all(),[ chris.friends.all(), [
'Tony' 'Tony'
], ],
attrgetter("name") attrgetter("name")
@ -229,7 +229,7 @@ class M2mThroughTests(TestCase):
) )
# Since this isn't a symmetrical relation, Tony's friend link still exists. # Since this isn't a symmetrical relation, Tony's friend link still exists.
self.assertQuerysetEqual( self.assertQuerysetEqual(
tony.friends.all(),[ tony.friends.all(), [
'Chris' 'Chris'
], ],
attrgetter("name") attrgetter("name")
@ -253,7 +253,7 @@ class M2mThroughTests(TestCase):
# We can query for the related model by using its attribute name (members, in # We can query for the related model by using its attribute name (members, in
# this case). # this case).
self.assertQuerysetEqual( self.assertQuerysetEqual(
Group.objects.filter(members__name='Bob'),[ Group.objects.filter(members__name='Bob'), [
'Roll' 'Roll'
], ],
attrgetter("name") attrgetter("name")
@ -262,7 +262,7 @@ class M2mThroughTests(TestCase):
# To query through the intermediary model, we specify its model name. # To query through the intermediary model, we specify its model name.
# In this case, membership. # In this case, membership.
self.assertQuerysetEqual( self.assertQuerysetEqual(
Group.objects.filter(membership__invite_reason="She was just awesome."),[ Group.objects.filter(membership__invite_reason="She was just awesome."), [
'Rock' 'Rock'
], ],
attrgetter("name") attrgetter("name")
@ -271,7 +271,7 @@ class M2mThroughTests(TestCase):
# If we want to query in the reverse direction by the related model, use its # If we want to query in the reverse direction by the related model, use its
# model name (group, in this case). # model name (group, in this case).
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(group__name="Rock"),[ Person.objects.filter(group__name="Rock"), [
'Jane', 'Jane',
'Jim' 'Jim'
], ],
@ -282,7 +282,7 @@ class M2mThroughTests(TestCase):
CustomMembership.objects.create(person=self.jim, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock)
# If the m2m field has specified a related_name, using that will work. # If the m2m field has specified a related_name, using that will work.
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(custom__name="Rock"),[ Person.objects.filter(custom__name="Rock"), [
'Bob', 'Bob',
'Jim' 'Jim'
], ],
@ -292,7 +292,7 @@ class M2mThroughTests(TestCase):
# To query through the intermediary model in the reverse direction, we again # To query through the intermediary model in the reverse direction, we again
# specify its model name (membership, in this case). # specify its model name (membership, in this case).
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(membership__invite_reason="She was just awesome."),[ Person.objects.filter(membership__invite_reason="She was just awesome."), [
'Jane' 'Jane'
], ],
attrgetter("name") attrgetter("name")
@ -300,7 +300,7 @@ class M2mThroughTests(TestCase):
# Let's see all of the groups that Jane joined after 1 Jan 2005: # Let's see all of the groups that Jane joined after 1 Jan 2005:
self.assertQuerysetEqual( self.assertQuerysetEqual(
Group.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__person=self.jane),[ Group.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__person=self.jane), [
'Rock' 'Rock'
], ],
attrgetter("name") attrgetter("name")
@ -309,7 +309,7 @@ class M2mThroughTests(TestCase):
# Queries also work in the reverse direction: Now let's see all of the people # Queries also work in the reverse direction: Now let's see all of the people
# that have joined Rock since 1 Jan 2005: # that have joined Rock since 1 Jan 2005:
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__group=self.rock),[ Person.objects.filter(membership__date_joined__gt=datetime(2005, 1, 1), membership__group=self.rock), [
'Jane', 'Jane',
'Jim' 'Jim'
], ],
@ -320,7 +320,7 @@ class M2mThroughTests(TestCase):
# querysets. To demonstrate this, we query for all people who have joined a # querysets. To demonstrate this, we query for all people who have joined a
# group after 2004: # group after 2004:
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)),[ Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)), [
'Jane', 'Jane',
'Jim', 'Jim',
'Jim' 'Jim'
@ -335,7 +335,7 @@ class M2mThroughTests(TestCase):
) )
# QuerySet's distinct() method can correct this problem. # QuerySet's distinct() method can correct this problem.
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)).distinct(),[ Person.objects.filter(membership__date_joined__gt=datetime(2004, 1, 1)).distinct(), [
'Jane', 'Jane',
'Jim' 'Jim'
], ],

View File

@ -150,12 +150,12 @@ class ToFieldThroughTests(TestCase):
def test_to_field_clear_reverse(self): def test_to_field_clear_reverse(self):
self.driver.car_set.clear() self.driver.car_set.clear()
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.driver.car_set.all(),[]) self.driver.car_set.all(), [])
def test_to_field_clear(self): def test_to_field_clear(self):
self.car.drivers.clear() self.car.drivers.clear()
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.car.drivers.all(),[]) self.car.drivers.all(), [])
# Low level tests for _add_items and _remove_items. We test these methods # Low level tests for _add_items and _remove_items. We test these methods
# because .add/.remove aren't available for m2m fields with through, but # because .add/.remove aren't available for m2m fields with through, but
@ -214,7 +214,7 @@ class ToFieldThroughTests(TestCase):
) )
self.car.drivers._remove_items('car', 'driver', self.driver) self.car.drivers._remove_items('car', 'driver', self.driver)
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.car.drivers.all(),[]) self.car.drivers.all(), [])
def test_remove_reverse(self): def test_remove_reverse(self):
self.assertQuerysetEqual( self.assertQuerysetEqual(
@ -223,7 +223,7 @@ class ToFieldThroughTests(TestCase):
) )
self.driver.car_set._remove_items('driver', 'car', self.car) self.driver.car_set._remove_items('driver', 'car', self.car)
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.driver.car_set.all(),[]) self.driver.car_set.all(), [])
class ThroughLoadDataTestCase(TestCase): class ThroughLoadDataTestCase(TestCase):

View File

@ -172,7 +172,7 @@ class ManyToManyTests(TestCase):
self.assertEqual(Article.objects.filter(publications__title__startswith="Science").count(), 4) self.assertEqual(Article.objects.filter(publications__title__startswith="Science").count(), 4)
self.assertEqual(Article.objects.filter(publications__title__startswith="Science").distinct().count(), 3) self.assertEqual(Article.objects.filter(publications__title__startswith="Science").distinct().count(), 3)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(publications__in=[self.p1.id,self.p2.id]).distinct(), Article.objects.filter(publications__in=[self.p1.id, self.p2.id]).distinct(),
[ [
'<Article: Django lets you build Web apps easily>', '<Article: Django lets you build Web apps easily>',
'<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Earth>',
@ -180,7 +180,7 @@ class ManyToManyTests(TestCase):
'<Article: Oxygen-free diet works wonders>', '<Article: Oxygen-free diet works wonders>',
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(publications__in=[self.p1.id,self.p2]).distinct(), Article.objects.filter(publications__in=[self.p1.id, self.p2]).distinct(),
[ [
'<Article: Django lets you build Web apps easily>', '<Article: Django lets you build Web apps easily>',
'<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Earth>',
@ -188,7 +188,7 @@ class ManyToManyTests(TestCase):
'<Article: Oxygen-free diet works wonders>', '<Article: Oxygen-free diet works wonders>',
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(publications__in=[self.p1,self.p2]).distinct(), Article.objects.filter(publications__in=[self.p1, self.p2]).distinct(),
[ [
'<Article: Django lets you build Web apps easily>', '<Article: Django lets you build Web apps easily>',
'<Article: NASA finds intelligent life on Earth>', '<Article: NASA finds intelligent life on Earth>',
@ -227,7 +227,7 @@ class ManyToManyTests(TestCase):
['<Publication: The Python Journal>']) ['<Publication: The Python Journal>'])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Publication.objects.filter(article__in=[self.a1.id,self.a2.id]).distinct(), Publication.objects.filter(article__in=[self.a1.id, self.a2.id]).distinct(),
[ [
'<Publication: Highlights for Children>', '<Publication: Highlights for Children>',
'<Publication: Science News>', '<Publication: Science News>',
@ -235,7 +235,7 @@ class ManyToManyTests(TestCase):
'<Publication: The Python Journal>', '<Publication: The Python Journal>',
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Publication.objects.filter(article__in=[self.a1.id,self.a2]).distinct(), Publication.objects.filter(article__in=[self.a1.id, self.a2]).distinct(),
[ [
'<Publication: Highlights for Children>', '<Publication: Highlights for Children>',
'<Publication: Science News>', '<Publication: Science News>',
@ -243,7 +243,7 @@ class ManyToManyTests(TestCase):
'<Publication: The Python Journal>', '<Publication: The Python Journal>',
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Publication.objects.filter(article__in=[self.a1,self.a2]).distinct(), Publication.objects.filter(article__in=[self.a1, self.a2]).distinct(),
[ [
'<Publication: Highlights for Children>', '<Publication: Highlights for Children>',
'<Publication: Science News>', '<Publication: Science News>',

View File

@ -211,14 +211,14 @@ class ManyToOneTests(TestCase):
"<Article: This is a test>", "<Article: This is a test>",
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(reporter__in=[self.r.id,self.r2.id]).distinct(), Article.objects.filter(reporter__in=[self.r.id, self.r2.id]).distinct(),
[ [
"<Article: John's second story>", "<Article: John's second story>",
"<Article: Paul's story>", "<Article: Paul's story>",
"<Article: This is a test>", "<Article: This is a test>",
]) ])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Article.objects.filter(reporter__in=[self.r,self.r2]).distinct(), Article.objects.filter(reporter__in=[self.r, self.r2]).distinct(),
[ [
"<Article: John's second story>", "<Article: John's second story>",
"<Article: Paul's story>", "<Article: Paul's story>",
@ -258,13 +258,13 @@ class ManyToOneTests(TestCase):
self.assertQuerysetEqual(Reporter.objects.filter(article=self.a), self.assertQuerysetEqual(Reporter.objects.filter(article=self.a),
["<Reporter: John Smith>"]) ["<Reporter: John Smith>"])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Reporter.objects.filter(article__in=[self.a.id,a3.id]).distinct(), Reporter.objects.filter(article__in=[self.a.id, a3.id]).distinct(),
["<Reporter: John Smith>"]) ["<Reporter: John Smith>"])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Reporter.objects.filter(article__in=[self.a.id,a3]).distinct(), Reporter.objects.filter(article__in=[self.a.id, a3]).distinct(),
["<Reporter: John Smith>"]) ["<Reporter: John Smith>"])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Reporter.objects.filter(article__in=[self.a,a3]).distinct(), Reporter.objects.filter(article__in=[self.a, a3]).distinct(),
["<Reporter: John Smith>"]) ["<Reporter: John Smith>"])
self.assertQuerysetEqual( self.assertQuerysetEqual(
Reporter.objects.filter(article__headline__startswith='T'), Reporter.objects.filter(article__headline__startswith='T'),
@ -439,6 +439,6 @@ class ManyToOneTests(TestCase):
Article.objects.values_list, Article.objects.values_list,
'reporter__notafield') 'reporter__notafield')
self.assertRaisesMessage(FieldError, self.assertRaisesMessage(FieldError,
expected_message % ', '.join(['EXTRA',] + Article._meta.get_all_field_names()), expected_message % ', '.join(['EXTRA'] + Article._meta.get_all_field_names()),
Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list, Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list,
'notafield') 'notafield')

View File

@ -7,8 +7,8 @@ from .models import PersonWithDefaultMaxLengths, PersonWithCustomMaxLengths
class MaxLengthArgumentsTests(unittest.TestCase): class MaxLengthArgumentsTests(unittest.TestCase):
def verify_max_length(self, model,field,length): def verify_max_length(self, model, field, length):
self.assertEqual(model._meta.get_field(field).max_length,length) self.assertEqual(model._meta.get_field(field).max_length, length)
def test_default_max_lengths(self): def test_default_max_lengths(self):
self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75) self.verify_max_length(PersonWithDefaultMaxLengths, 'email', 75)

View File

@ -115,7 +115,7 @@ class ArticleForm(forms.ModelForm):
class PartialArticleForm(forms.ModelForm): class PartialArticleForm(forms.ModelForm):
class Meta: class Meta:
model = Article model = Article
fields = ('headline','pub_date') fields = ('headline', 'pub_date')
class RoykoForm(forms.ModelForm): class RoykoForm(forms.ModelForm):

View File

@ -178,9 +178,9 @@ class ManyToManyCallableInitialTests(TestCase):
return db_field.formfield(**kwargs) return db_field.formfield(**kwargs)
# Set up some Publications to use as data # Set up some Publications to use as data
book1 = Publication.objects.create(title="First Book", date_published=date(2007,1,1)) book1 = Publication.objects.create(title="First Book", date_published=date(2007, 1, 1))
book2 = Publication.objects.create(title="Second Book", date_published=date(2008,1,1)) book2 = Publication.objects.create(title="Second Book", date_published=date(2008, 1, 1))
book3 = Publication.objects.create(title="Third Book", date_published=date(2009,1,1)) book3 = Publication.objects.create(title="Third Book", date_published=date(2009, 1, 1))
# Create a ModelForm, instantiate it, and check that the output is as expected # Create a ModelForm, instantiate it, and check that the output is as expected
ModelForm = modelform_factory(Article, fields="__all__", ModelForm = modelform_factory(Article, fields="__all__",
@ -252,7 +252,7 @@ class OneToOneFieldTests(TestCase):
publication = Publication.objects.create(title="Pravda", publication = Publication.objects.create(title="Pravda",
date_published=date(1991, 8, 22)) date_published=date(1991, 8, 22))
author = Author.objects.create(publication=publication, full_name='John Doe') author = Author.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication':'', 'full_name':'John Doe'}, instance=author) form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
self.assertTrue(form.is_valid()) self.assertTrue(form.is_valid())
self.assertEqual(form.cleaned_data['publication'], None) self.assertEqual(form.cleaned_data['publication'], None)
author = form.save() author = form.save()
@ -270,7 +270,7 @@ class OneToOneFieldTests(TestCase):
publication = Publication.objects.create(title="Pravda", publication = Publication.objects.create(title="Pravda",
date_published=date(1991, 8, 22)) date_published=date(1991, 8, 22))
author = Author1.objects.create(publication=publication, full_name='John Doe') author = Author1.objects.create(publication=publication, full_name='John Doe')
form = AuthorForm({'publication':'', 'full_name':'John Doe'}, instance=author) form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
self.assertTrue(not form.is_valid()) self.assertTrue(not form.is_valid())
@ -350,7 +350,7 @@ class FormFieldCallbackTests(TestCase):
self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea)
# With a widget should not set the widget to textarea # With a widget should not set the widget to textarea
Form = modelform_factory(Person, fields="__all__", widgets={'name':widget}) Form = modelform_factory(Person, fields="__all__", widgets={'name': widget})
self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea) self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea)
def test_custom_callback(self): def test_custom_callback(self):

View File

@ -405,7 +405,7 @@ class FormfieldShouldDeleteFormTests(TestCase):
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update(dict(
('form-%d-id' % i, user.pk) ('form-%d-id' % i, user.pk)
for i,user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) ))
formset = self.NormalFormset(data, queryset=User.objects.all()) formset = self.NormalFormset(data, queryset=User.objects.all())
self.assertTrue(formset.is_valid()) self.assertTrue(formset.is_valid())
@ -422,7 +422,7 @@ class FormfieldShouldDeleteFormTests(TestCase):
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update(dict(
('form-%d-id' % i, user.pk) ('form-%d-id' % i, user.pk)
for i,user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) ))
data.update(self.delete_all_ids) data.update(self.delete_all_ids)
formset = self.NormalFormset(data, queryset=User.objects.all()) formset = self.NormalFormset(data, queryset=User.objects.all())
@ -441,7 +441,7 @@ class FormfieldShouldDeleteFormTests(TestCase):
data['form-INITIAL_FORMS'] = 4 data['form-INITIAL_FORMS'] = 4
data.update(dict( data.update(dict(
('form-%d-id' % i, user.pk) ('form-%d-id' % i, user.pk)
for i,user in enumerate(User.objects.all()) for i, user in enumerate(User.objects.all())
)) ))
data.update(self.delete_all_ids) data.update(self.delete_all_ids)
formset = self.DeleteFormset(data, queryset=User.objects.all()) formset = self.DeleteFormset(data, queryset=User.objects.all())

View File

@ -67,7 +67,7 @@ class Supplier(models.Model):
restaurant = models.ForeignKey(Restaurant) restaurant = models.ForeignKey(Restaurant)
class Wholesaler(Supplier): class Wholesaler(Supplier):
retailer = models.ForeignKey(Supplier,related_name='wholesale_supplier') retailer = models.ForeignKey(Supplier, related_name='wholesale_supplier')
class Parent(models.Model): class Parent(models.Model):
created = models.DateTimeField(default=datetime.datetime.now) created = models.DateTimeField(default=datetime.datetime.now)

View File

@ -52,21 +52,21 @@ class ModelInheritanceTest(TestCase):
places = list(Place.objects.all()) places = list(Place.objects.all())
self.assertEqual(places, [place1, place2]) self.assertEqual(places, [place1, place2])
dicts = list(Restaurant.objects.values('name','serves_hot_dogs')) dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'name': "Guido's House of Pasta", 'name': "Guido's House of Pasta",
'serves_hot_dogs': True 'serves_hot_dogs': True
}]) }])
dicts = list(ItalianRestaurant.objects.values( dicts = list(ItalianRestaurant.objects.values(
'name','serves_hot_dogs','serves_gnocchi')) 'name', 'serves_hot_dogs', 'serves_gnocchi'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'name': "Guido's House of Pasta", 'name': "Guido's House of Pasta",
'serves_gnocchi': True, 'serves_gnocchi': True,
'serves_hot_dogs': True, 'serves_hot_dogs': True,
}]) }])
dicts = list(ParkingLot.objects.values('name','capacity')) dicts = list(ParkingLot.objects.values('name', 'capacity'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'capacity': 100, 'capacity': 100,
'name': 'Main St', 'name': 'Main St',
@ -94,7 +94,7 @@ class ModelInheritanceTest(TestCase):
self.assertEqual(places[0].name, 'Derelict lot') self.assertEqual(places[0].name, 'Derelict lot')
self.assertEqual(places[1].name, "Guido's All New House of Pasta") self.assertEqual(places[1].name, "Guido's All New House of Pasta")
dicts = list(Restaurant.objects.values('name','serves_hot_dogs')) dicts = list(Restaurant.objects.values('name', 'serves_hot_dogs'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'name': "Guido's All New House of Pasta", 'name': "Guido's All New House of Pasta",
'serves_hot_dogs': False, 'serves_hot_dogs': False,
@ -108,7 +108,7 @@ class ModelInheritanceTest(TestCase):
'serves_hot_dogs': False, 'serves_hot_dogs': False,
}]) }])
dicts = list(ParkingLot.objects.values('name','capacity')) dicts = list(ParkingLot.objects.values('name', 'capacity'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'capacity': 50, 'capacity': 50,
'name': 'Derelict lot', 'name': 'Derelict lot',
@ -123,7 +123,7 @@ class ModelInheritanceTest(TestCase):
# Note that the name has not changed # Note that the name has not changed
# - name is an attribute of Place, not ItalianRestaurant # - name is an attribute of Place, not ItalianRestaurant
dicts = list(ItalianRestaurant.objects.values( dicts = list(ItalianRestaurant.objects.values(
'name','serves_hot_dogs','serves_gnocchi')) 'name', 'serves_hot_dogs', 'serves_gnocchi'))
self.assertEqual(dicts, [{ self.assertEqual(dicts, [{
'name': "Guido's All New House of Pasta", 'name': "Guido's All New House of Pasta",
'serves_gnocchi': False, 'serves_gnocchi': False,

View File

@ -654,7 +654,7 @@ class ValidationTests(unittest.TestCase):
class ValidationTestModelAdmin(ModelAdmin): class ValidationTestModelAdmin(ModelAdmin):
fieldsets = (("General", {"fields": ("name",)}),) fieldsets = (("General", {"fields": ("name",)}),)
fields = ["name",] fields = ["name"]
six.assertRaisesRegex(self, six.assertRaisesRegex(self,
ImproperlyConfigured, ImproperlyConfigured,

View File

@ -522,37 +522,37 @@ class QueryTestCase(TestCase):
self.assertEqual(chris._state.db, 'other') self.assertEqual(chris._state.db, 'other')
self.assertEqual(html5._state.db, 'other') self.assertEqual(html5._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(Person.objects.using('other').values_list('name',flat=True)), 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)), 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' # When saved (no using required), new objects goes to 'other'
chris.save() chris.save()
html5.save() html5.save()
self.assertEqual(list(Person.objects.using('default').values_list('name',flat=True)), 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)), 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)), 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)), 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 # 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) water = Book(title="Dive into Water", published=datetime.date(2001, 1, 1), editor=mark)
self.assertEqual(water._state.db, 'other') self.assertEqual(water._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), 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)), 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' # When saved, the new book goes to 'other'
water.save() water.save()
self.assertEqual(list(Book.objects.using('default').values_list('title',flat=True)), 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)), 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): def test_foreign_key_deletion(self):
@ -657,40 +657,40 @@ class QueryTestCase(TestCase):
self.assertEqual(charlie._state.db, 'other') self.assertEqual(charlie._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(User.objects.using('other').values_list('username',flat=True)), 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)), 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' # When saved (no using required), new objects goes to 'other'
charlie.save() charlie.save()
bob_profile.save() bob_profile.save()
new_bob_profile.save() new_bob_profile.save()
self.assertEqual(list(User.objects.using('default').values_list('username',flat=True)), 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)), 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)), 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)), 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 # This also works if you assign the O2O relation in the constructor
denise = User.objects.db_manager('other').create_user('denise','denise@example.com') denise = User.objects.db_manager('other').create_user('denise', 'denise@example.com')
denise_profile = UserProfile(flavor="tofu", user=denise) denise_profile = UserProfile(flavor="tofu", user=denise)
self.assertEqual(denise_profile._state.db, 'other') self.assertEqual(denise_profile._state.db, 'other')
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), 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)), 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' # When saved, the new profile goes to 'other'
denise_profile.save() denise_profile.save()
self.assertEqual(list(UserProfile.objects.using('default').values_list('flavor',flat=True)), 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)), 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): def test_generic_key_separation(self):
@ -805,14 +805,14 @@ class QueryTestCase(TestCase):
# ... but it isn't saved yet # ... but it isn't saved yet
self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), 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)), 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' # When saved, John goes to 'other'
review3.save() review3.save()
self.assertEqual(list(Review.objects.using('default').filter(object_id=pro.pk).values_list('source', flat=True)), 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)), 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): def test_generic_key_deletion(self):
@ -1066,7 +1066,7 @@ class RouterTestCase(TestCase):
self.assertFalse(created) self.assertFalse(created)
book, created = Book.objects.get_or_create(title="Dive Into Python", book, created = Book.objects.get_or_create(title="Dive Into Python",
defaults={'published':datetime.date(2009, 5, 4)}) defaults={'published': datetime.date(2009, 5, 4)})
self.assertTrue(created) self.assertTrue(created)
# Check the head count of objects # Check the head count of objects

View File

@ -443,9 +443,9 @@ class ForeignKeyToFieldTest(TestCase):
self.assertEqual( self.assertEqual(
favorites, favorites,
[ [
([six.text_type(self.author2)],[six.text_type(self.author3)]), ([six.text_type(self.author2)], [six.text_type(self.author3)]),
([six.text_type(self.author3)],[six.text_type(self.author1)]), ([six.text_type(self.author3)], [six.text_type(self.author1)]),
([six.text_type(self.author1)],[six.text_type(self.author2)]) ([six.text_type(self.author1)], [six.text_type(self.author2)])
] ]
) )

View File

@ -1915,16 +1915,16 @@ class SubqueryTests(TestCase):
"Subselects honor any manual ordering" "Subselects honor any manual ordering"
try: try:
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2]) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3,4])) self.assertEqual(set(query.values_list('id', flat=True)), set([3, 4]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2]) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3,4])) self.assertEqual(set(query.values_list('id', flat=True)), set([3, 4]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2])
self.assertEqual(set(query.values_list('id', flat=True)), set([3])) self.assertEqual(set(query.values_list('id', flat=True)), set([3]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:]) query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[2:])
self.assertEqual(set(query.values_list('id', flat=True)), set([1,2])) self.assertEqual(set(query.values_list('id', flat=True)), set([1, 2]))
except DatabaseError as e: except DatabaseError as e:
# Oracle and MySQL both have problems with sliced subselects. # Oracle and MySQL both have problems with sliced subselects.
# This prevents us from even evaluating this test case at all. # This prevents us from even evaluating this test case at all.
@ -1937,7 +1937,7 @@ class SubqueryTests(TestCase):
""" """
try: try:
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2] query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:2])[0:2]
self.assertEqual(set([x.id for x in query]), set([3,4])) self.assertEqual(set([x.id for x in query]), set([3, 4]))
query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3] query = DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:3])[1:3]
self.assertEqual(set([x.id for x in query]), set([3])) self.assertEqual(set([x.id for x in query]), set([3]))
@ -1954,10 +1954,10 @@ class SubqueryTests(TestCase):
"Delete queries can safely contain sliced subqueries" "Delete queries can safely contain sliced subqueries"
try: try:
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete() DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[0:1]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1,2,3])) self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1, 2, 3]))
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete() DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:2]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1,3])) self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([1, 3]))
DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete() DumbCategory.objects.filter(id__in=DumbCategory.objects.order_by('-id')[1:]).delete()
self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([3])) self.assertEqual(set(DumbCategory.objects.values_list('id', flat=True)), set([3]))
@ -2139,7 +2139,7 @@ class EscapingTests(TestCase):
['<ReservedName: b>', '<ReservedName: a>'] ['<ReservedName: b>', '<ReservedName: a>']
) )
self.assertQuerysetEqual( self.assertQuerysetEqual(
ReservedName.objects.extra(select={'stuff':'name'}, order_by=('order','stuff')), ReservedName.objects.extra(select={'stuff': 'name'}, order_by=('order', 'stuff')),
['<ReservedName: b>', '<ReservedName: a>'] ['<ReservedName: b>', '<ReservedName: a>']
) )

View File

@ -29,7 +29,7 @@ class Event(models.Model):
class Happening(models.Model): class Happening(models.Model):
when = models.DateTimeField(blank=True, default=datetime.datetime.now) when = models.DateTimeField(blank=True, default=datetime.datetime.now)
name = models.CharField(blank=True, max_length=100, default=lambda:"test") name = models.CharField(blank=True, max_length=100, default=lambda: "test")
number1 = models.IntegerField(blank=True, default=standalone_number) number1 = models.IntegerField(blank=True, default=standalone_number)
number2 = models.IntegerField(blank=True, default=Numbers.get_static_number) number2 = models.IntegerField(blank=True, default=Numbers.get_static_number)
number3 = models.IntegerField(blank=True, default=Numbers.get_class_number) number3 = models.IntegerField(blank=True, default=Numbers.get_class_number)

View File

@ -32,11 +32,11 @@ class RawQueryTests(TestCase):
for field in model._meta.fields: for field in model._meta.fields:
# Check that all values on the model are equal # Check that all values on the model are equal
self.assertEqual(getattr(item,field.attname), self.assertEqual(getattr(item, field.attname),
getattr(orig_item,field.attname)) getattr(orig_item, field.attname))
# This includes checking that they are the same type # This includes checking that they are the same type
self.assertEqual(type(getattr(item,field.attname)), self.assertEqual(type(getattr(item, field.attname)),
type(getattr(orig_item,field.attname))) type(getattr(orig_item, field.attname)))
def assertNoAnnotations(self, results): def assertNoAnnotations(self, results):
""" """

View File

@ -27,9 +27,9 @@ class SelectRelatedRegressTests(TestCase):
dev1 = Device.objects.create(name="router", building=b) dev1 = Device.objects.create(name="router", building=b)
dev2 = Device.objects.create(name="switch", building=b) dev2 = Device.objects.create(name="switch", building=b)
dev3 = Device.objects.create(name="server", building=b) dev3 = Device.objects.create(name="server", building=b)
port1 = Port.objects.create(port_number='4',device=dev1) port1 = Port.objects.create(port_number='4', device=dev1)
port2 = Port.objects.create(port_number='7',device=dev2) port2 = Port.objects.create(port_number='7', device=dev2)
port3 = Port.objects.create(port_number='1',device=dev3) port3 = Port.objects.create(port_number='1', device=dev3)
c1 = Connection.objects.create(start=port1, end=port2) c1 = Connection.objects.create(start=port1, end=port2)
c2 = Connection.objects.create(start=port2, end=port3) c2 = Connection.objects.create(start=port2, end=port3)

View File

@ -144,7 +144,7 @@ class SerializersTestBase(object):
serialized field list - it replaces the pk identifier. serialized field list - it replaces the pk identifier.
""" """
profile = AuthorProfile(author=self.joe, profile = AuthorProfile(author=self.joe,
date_of_birth=datetime(1970,1,1)) date_of_birth=datetime(1970, 1, 1))
profile.save() profile.save()
serial_str = serializers.serialize(self.serializer_name, serial_str = serializers.serialize(self.serializer_name,
AuthorProfile.objects.all()) AuthorProfile.objects.all())
@ -155,7 +155,7 @@ class SerializersTestBase(object):
def test_serialize_field_subset(self): def test_serialize_field_subset(self):
"""Tests that output can be restricted to a subset of fields""" """Tests that output can be restricted to a subset of fields"""
valid_fields = ('headline','pub_date') valid_fields = ('headline', 'pub_date')
invalid_fields = ("author", "categories") invalid_fields = ("author", "categories")
serial_str = serializers.serialize(self.serializer_name, serial_str = serializers.serialize(self.serializer_name,
Article.objects.all(), Article.objects.all(),

View File

@ -102,7 +102,7 @@ def pk_create(pk, klass, data):
return [instance] return [instance]
def inherited_create(pk, klass, data): def inherited_create(pk, klass, data):
instance = klass(id=pk,**data) instance = klass(id=pk, **data)
# This isn't a raw save because: # This isn't a raw save because:
# 1) we're testing inheritance, not field behavior, so none # 1) we're testing inheritance, not field behavior, so none
# of the field values need to be protected. # of the field values need to be protected.
@ -110,7 +110,7 @@ def inherited_create(pk, klass, data):
# automatically is easier than manually creating both. # automatically is easier than manually creating both.
models.Model.save(instance) models.Model.save(instance)
created = [instance] created = [instance]
for klass,field in instance._meta.parents.items(): for klass, field in instance._meta.parents.items():
created.append(klass.objects.get(id=pk)) created.append(klass.objects.get(id=pk))
return created return created
@ -166,8 +166,8 @@ def pk_compare(testcase, pk, klass, data):
def inherited_compare(testcase, pk, klass, data): def inherited_compare(testcase, pk, klass, data):
instance = klass.objects.get(id=pk) instance = klass.objects.get(id=pk)
for key,value in data.items(): for key, value in data.items():
testcase.assertEqual(value, getattr(instance,key)) testcase.assertEqual(value, getattr(instance, key))
# Define some data types. Each data type is # Define some data types. Each data type is
# actually a pair of functions; one to create # actually a pair of functions; one to create
@ -197,9 +197,9 @@ test_data = [
# (We use something that will fit into a latin1 database encoding here, # (We use something that will fit into a latin1 database encoding here,
# because that is still the default used on many system setups.) # because that is still the default used on many system setups.)
(data_obj, 16, CharData, '\xa5'), (data_obj, 16, CharData, '\xa5'),
(data_obj, 20, DateData, datetime.date(2006,6,16)), (data_obj, 20, DateData, datetime.date(2006, 6, 16)),
(data_obj, 21, DateData, None), (data_obj, 21, DateData, None),
(data_obj, 30, DateTimeData, datetime.datetime(2006,6,16,10,42,37)), (data_obj, 30, DateTimeData, datetime.datetime(2006, 6, 16, 10, 42, 37)),
(data_obj, 31, DateTimeData, None), (data_obj, 31, DateTimeData, None),
(data_obj, 40, EmailData, "hovercraft@example.com"), (data_obj, 40, EmailData, "hovercraft@example.com"),
(data_obj, 41, EmailData, None), (data_obj, 41, EmailData, None),
@ -247,7 +247,7 @@ Several of them.
The end."""), The end."""),
(data_obj, 161, TextData, ""), (data_obj, 161, TextData, ""),
(data_obj, 162, TextData, None), (data_obj, 162, TextData, None),
(data_obj, 170, TimeData, datetime.time(10,42,37)), (data_obj, 170, TimeData, datetime.time(10, 42, 37)),
(data_obj, 171, TimeData, None), (data_obj, 171, TimeData, None),
(generic_obj, 200, GenericData, ['Generic Object 1', 'tag1', 'tag2']), (generic_obj, 200, GenericData, ['Generic Object 1', 'tag1', 'tag2']),
@ -262,9 +262,9 @@ The end."""),
(fk_obj, 402, FKData, None), # Empty reference (fk_obj, 402, FKData, None), # Empty reference
(m2m_obj, 410, M2MData, []), # Empty set (m2m_obj, 410, M2MData, []), # Empty set
(m2m_obj, 411, M2MData, [300,301]), # Post reference (m2m_obj, 411, M2MData, [300, 301]), # Post reference
(m2m_obj, 412, M2MData, [500,501]), # Pre reference (m2m_obj, 412, M2MData, [500, 501]), # Pre reference
(m2m_obj, 413, M2MData, [300,301,500,501]), # Pre and Post reference (m2m_obj, 413, M2MData, [300, 301, 500, 501]), # Pre and Post reference
(o2o_obj, None, O2OData, 300), # Post reference (o2o_obj, None, O2OData, 300), # Post reference
(o2o_obj, None, O2OData, 500), # Pre reference (o2o_obj, None, O2OData, 500), # Pre reference
@ -308,8 +308,8 @@ The end."""),
(pk_obj, 601, BooleanPKData, True), (pk_obj, 601, BooleanPKData, True),
(pk_obj, 602, BooleanPKData, False), (pk_obj, 602, BooleanPKData, False),
(pk_obj, 610, CharPKData, "Test Char PKData"), (pk_obj, 610, CharPKData, "Test Char PKData"),
# (pk_obj, 620, DatePKData, datetime.date(2006,6,16)), # (pk_obj, 620, DatePKData, datetime.date(2006, 6, 16)),
# (pk_obj, 630, DateTimePKData, datetime.datetime(2006,6,16,10,42,37)), # (pk_obj, 630, DateTimePKData, datetime.datetime(2006, 6, 16, 10, 42, 37)),
(pk_obj, 640, EmailPKData, "hovercraft@example.com"), (pk_obj, 640, EmailPKData, "hovercraft@example.com"),
# (pk_obj, 650, FilePKData, 'file:///foo/bar/whiz.txt'), # (pk_obj, 650, FilePKData, 'file:///foo/bar/whiz.txt'),
(pk_obj, 660, FilePathPKData, "/foo/bar/whiz.txt"), (pk_obj, 660, FilePathPKData, "/foo/bar/whiz.txt"),
@ -337,15 +337,15 @@ The end."""),
# It contains line breaks. # It contains line breaks.
# Several of them. # Several of them.
# The end."""), # The end."""),
# (pk_obj, 770, TimePKData, datetime.time(10,42,37)), # (pk_obj, 770, TimePKData, datetime.time(10, 42, 37)),
# (pk_obj, 790, XMLPKData, "<foo></foo>"), # (pk_obj, 790, XMLPKData, "<foo></foo>"),
(data_obj, 800, AutoNowDateTimeData, datetime.datetime(2006,6,16,10,42,37)), (data_obj, 800, AutoNowDateTimeData, datetime.datetime(2006, 6, 16, 10, 42, 37)),
(data_obj, 810, ModifyingSaveData, 42), (data_obj, 810, ModifyingSaveData, 42),
(inherited_obj, 900, InheritAbstractModel, {'child_data':37,'parent_data':42}), (inherited_obj, 900, InheritAbstractModel, {'child_data': 37, 'parent_data': 42}),
(inherited_obj, 910, ExplicitInheritBaseModel, {'child_data':37,'parent_data':42}), (inherited_obj, 910, ExplicitInheritBaseModel, {'child_data': 37, 'parent_data': 42}),
(inherited_obj, 920, InheritBaseModel, {'child_data':37,'parent_data':42}), (inherited_obj, 920, InheritBaseModel, {'child_data': 37, 'parent_data': 42}),
(data_obj, 1000, BigIntegerData, 9223372036854775807), (data_obj, 1000, BigIntegerData, 9223372036854775807),
(data_obj, 1001, BigIntegerData, -9223372036854775808), (data_obj, 1001, BigIntegerData, -9223372036854775808),
@ -502,7 +502,7 @@ def fieldsTest(format, self):
obj.save_base(raw=True) obj.save_base(raw=True)
# Serialize then deserialize the test database # Serialize then deserialize the test database
serialized_data = serializers.serialize(format, [obj], indent=2, fields=('field1','field3')) serialized_data = serializers.serialize(format, [obj], indent=2, fields=('field1', 'field3'))
result = next(serializers.deserialize(format, serialized_data)) result = next(serializers.deserialize(format, serialized_data))
# Check that the deserialized object contains data in only the serialized fields. # Check that the deserialized object contains data in only the serialized fields.
@ -511,7 +511,7 @@ def fieldsTest(format, self):
self.assertEqual(result.object.field3, 'third') self.assertEqual(result.object.field3, 'third')
def streamTest(format, self): def streamTest(format, self):
obj = ComplexModel(field1='first',field2='second',field3='third') obj = ComplexModel(field1='first', field2='second', field3='third')
obj.save_base(raw=True) obj.save_base(raw=True)
# Serialize the test database to a stream # Serialize the test database to a stream
@ -531,7 +531,7 @@ def streamTest(format, self):
def naturalKeyTest(format, self): def naturalKeyTest(format, self):
book1 = {'data': '978-1590597255', 'title': 'The Definitive Guide to ' book1 = {'data': '978-1590597255', 'title': 'The Definitive Guide to '
'Django: Web Development Done Right'} 'Django: Web Development Done Right'}
book2 = {'data':'978-1590599969', 'title': 'Practical Django Projects'} book2 = {'data': '978-1590599969', 'title': 'Practical Django Projects'}
# Create the books. # Create the books.
adrian = NaturalKeyAnchor.objects.create(**book1) adrian = NaturalKeyAnchor.objects.create(**book1)

View File

@ -43,11 +43,11 @@ def get_filter_tests():
'filter-timesince03' : ('{{ a|timesince }}', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds = 10)}, '1\xa0hour, 25\xa0minutes'), 'filter-timesince03' : ('{{ a|timesince }}', {'a': datetime.now() - timedelta(hours=1, minutes=25, seconds = 10)}, '1\xa0hour, 25\xa0minutes'),
# Compare to a given parameter # Compare to a given parameter
'filter-timesince04' : ('{{ a|timesince:b }}', {'a':now - timedelta(days=2), 'b':now - timedelta(days=1)}, '1\xa0day'), 'filter-timesince04' : ('{{ a|timesince:b }}', {'a': now - timedelta(days=2), 'b': now - timedelta(days=1)}, '1\xa0day'),
'filter-timesince05' : ('{{ a|timesince:b }}', {'a':now - timedelta(days=2, minutes=1), 'b':now - timedelta(days=2)}, '1\xa0minute'), 'filter-timesince05' : ('{{ a|timesince:b }}', {'a': now - timedelta(days=2, minutes=1), 'b': now - timedelta(days=2)}, '1\xa0minute'),
# Check that timezone is respected # Check that timezone is respected
'filter-timesince06' : ('{{ a|timesince:b }}', {'a':now_tz - timedelta(hours=8), 'b':now_tz}, '8\xa0hours'), 'filter-timesince06' : ('{{ a|timesince:b }}', {'a': now_tz - timedelta(hours=8), 'b': now_tz}, '8\xa0hours'),
# Regression for #7443 # Regression for #7443
'filter-timesince07': ('{{ earlier|timesince }}', {'earlier': now - timedelta(days=7)}, '1\xa0week'), 'filter-timesince07': ('{{ earlier|timesince }}', {'earlier': now - timedelta(days=7)}, '1\xa0week'),
@ -69,13 +69,13 @@ def get_filter_tests():
'filter-timesince18' : ('{{ a|timesince:b }}', {'a': today, 'b': today + timedelta(hours=24)}, '1\xa0day'), 'filter-timesince18' : ('{{ a|timesince:b }}', {'a': today, 'b': today + timedelta(hours=24)}, '1\xa0day'),
# Default compare with datetime.now() # Default compare with datetime.now()
'filter-timeuntil01' : ('{{ a|timeuntil }}', {'a':datetime.now() + timedelta(minutes=2, seconds = 10)}, '2\xa0minutes'), 'filter-timeuntil01' : ('{{ a|timeuntil }}', {'a': datetime.now() + timedelta(minutes=2, seconds=10)}, '2\xa0minutes'),
'filter-timeuntil02' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(days=1, seconds = 10))}, '1\xa0day'), 'filter-timeuntil02' : ('{{ a|timeuntil }}', {'a': (datetime.now() + timedelta(days=1, seconds=10))}, '1\xa0day'),
'filter-timeuntil03' : ('{{ a|timeuntil }}', {'a':(datetime.now() + timedelta(hours=8, minutes=10, seconds = 10))}, '8\xa0hours, 10\xa0minutes'), 'filter-timeuntil03' : ('{{ a|timeuntil }}', {'a': (datetime.now() + timedelta(hours=8, minutes=10, seconds = 10))}, '8\xa0hours, 10\xa0minutes'),
# Compare to a given parameter # Compare to a given parameter
'filter-timeuntil04' : ('{{ a|timeuntil:b }}', {'a':now - timedelta(days=1), 'b':now - timedelta(days=2)}, '1\xa0day'), 'filter-timeuntil04' : ('{{ a|timeuntil:b }}', {'a': now - timedelta(days=1), 'b': now - timedelta(days=2)}, '1\xa0day'),
'filter-timeuntil05' : ('{{ a|timeuntil:b }}', {'a':now - timedelta(days=2), 'b':now - timedelta(days=2, minutes=1)}, '1\xa0minute'), 'filter-timeuntil05' : ('{{ a|timeuntil:b }}', {'a': now - timedelta(days=2), 'b': now - timedelta(days=2, minutes=1)}, '1\xa0minute'),
# Regression for #7443 # Regression for #7443
'filter-timeuntil06': ('{{ earlier|timeuntil }}', {'earlier': now - timedelta(days=7)}, '0\xa0minutes'), 'filter-timeuntil06': ('{{ earlier|timeuntil }}', {'earlier': now - timedelta(days=7)}, '0\xa0minutes'),

View File

@ -145,7 +145,7 @@ class SimpleTemplateResponseTest(TestCase):
# When the content is rendered, all the callbacks are invoked, too. # When the content is rendered, all the callbacks are invoked, too.
response.render() response.render()
self.assertEqual(response.content, b'First template\n') self.assertEqual(response.content, b'First template\n')
self.assertEqual(post, ['post1','post2']) self.assertEqual(post, ['post1', 'post2'])
def test_pickling(self): def test_pickling(self):
# Create a template response. The context is # Create a template response. The context is

View File

@ -23,13 +23,13 @@ class SmartIfTests(unittest.TestCase):
self.assertTrue(var.eval({})) self.assertTrue(var.eval({}))
def test_in(self): def test_in(self):
list_ = [1,2,3] list_ = [1, 2, 3]
self.assertCalcEqual(True, [1, 'in', list_]) self.assertCalcEqual(True, [1, 'in', list_])
self.assertCalcEqual(False, [1, 'in', None]) self.assertCalcEqual(False, [1, 'in', None])
self.assertCalcEqual(False, [None, 'in', list_]) self.assertCalcEqual(False, [None, 'in', list_])
def test_not_in(self): def test_not_in(self):
list_ = [1,2,3] list_ = [1, 2, 3]
self.assertCalcEqual(False, [1, 'not', 'in', list_]) self.assertCalcEqual(False, [1, 'not', 'in', list_])
self.assertCalcEqual(True, [4, 'not', 'in', list_]) self.assertCalcEqual(True, [4, 'not', 'in', list_])
self.assertCalcEqual(False, [1, 'not', 'in', None]) self.assertCalcEqual(False, [1, 'not', 'in', None])

View File

@ -568,7 +568,7 @@ class TemplateTests(TransRealMixin, TestCase):
# Warm the URL reversing cache. This ensures we don't pay the cost # Warm the URL reversing cache. This ensures we don't pay the cost
# warming the cache during one of the tests. # warming the cache during one of the tests.
urlresolvers.reverse('template_tests.views.client_action', urlresolvers.reverse('template_tests.views.client_action',
kwargs={'id':0,'action':"update"}) kwargs={'id': 0, 'action': "update"})
for name, vals in tests: for name, vals in tests:
if isinstance(vals[2], tuple): if isinstance(vals[2], tuple):
@ -665,13 +665,13 @@ class TemplateTests(TransRealMixin, TestCase):
# Variables should be replaced with their value in the current # Variables should be replaced with their value in the current
# context # context
'basic-syntax02': ("{{ headline }}", {'headline':'Success'}, "Success"), 'basic-syntax02': ("{{ headline }}", {'headline': 'Success'}, "Success"),
# More than one replacement variable is allowed in a template # More than one replacement variable is allowed in a template
'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"), 'basic-syntax03': ("{{ first }} --- {{ second }}", {"first" : 1, "second" : 2}, "1 --- 2"),
# Fail silently when a variable is not found in the current context # Fail silently when a variable is not found in the current context
'basic-syntax04': ("as{{ missing }}df", {}, ("asdf","asINVALIDdf")), 'basic-syntax04': ("as{{ missing }}df", {}, ("asdf", "asINVALIDdf")),
# A variable may not contain more than one word # A variable may not contain more than one word
'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError), 'basic-syntax06': ("{{ multi word variable }}", {}, template.TemplateSyntaxError),
@ -687,7 +687,7 @@ class TemplateTests(TransRealMixin, TestCase):
'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"), 'basic-syntax10': ("{{ var.otherclass.method }}", {"var": SomeClass()}, "OtherClass.method"),
# Fail silently when a variable's attribute isn't found # Fail silently when a variable's attribute isn't found
'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ("","INVALID")), 'basic-syntax11': ("{{ var.blech }}", {"var": SomeClass()}, ("", "INVALID")),
# Raise TemplateSyntaxError when trying to access a variable beginning with an underscore # Raise TemplateSyntaxError when trying to access a variable beginning with an underscore
'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError), 'basic-syntax12': ("{{ var.__dict__ }}", {"var": SomeClass()}, template.TemplateSyntaxError),
@ -700,13 +700,13 @@ class TemplateTests(TransRealMixin, TestCase):
'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError), 'basic-syntax17': ("{{ moo? }}", {}, template.TemplateSyntaxError),
# Attribute syntax allows a template to call a dictionary key's value # Attribute syntax allows a template to call a dictionary key's value
'basic-syntax18': ("{{ foo.bar }}", {"foo" : {"bar" : "baz"}}, "baz"), 'basic-syntax18': ("{{ foo.bar }}", {"foo": {"bar": "baz"}}, "baz"),
# Fail silently when a variable's dictionary key isn't found # Fail silently when a variable's dictionary key isn't found
'basic-syntax19': ("{{ foo.spam }}", {"foo" : {"bar" : "baz"}}, ("","INVALID")), 'basic-syntax19': ("{{ foo.spam }}", {"foo": {"bar": "baz"}}, ("", "INVALID")),
# Fail silently when accessing a non-simple method # Fail silently when accessing a non-simple method
'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ("","INVALID")), 'basic-syntax20': ("{{ var.method2 }}", {"var": SomeClass()}, ("", "INVALID")),
# Don't silence a TypeError if it was raised inside a callable # Don't silence a TypeError if it was raised inside a callable
'basic-syntax20b': ("{{ var.method5 }}", {"var": SomeClass()}, TypeError), 'basic-syntax20b': ("{{ var.method5 }}", {"var": SomeClass()}, TypeError),
@ -893,18 +893,18 @@ class TemplateTests(TransRealMixin, TestCase):
'cycle11': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}", {}, 'abc'), 'cycle11': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}", {}, 'abc'),
'cycle12': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, 'abca'), 'cycle12': ("{% cycle 'a' 'b' 'c' as abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, 'abca'),
'cycle13': ("{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'), 'cycle13': ("{% for i in test %}{% cycle 'a' 'b' %}{{ i }},{% endfor %}", {'test': range(5)}, 'a0,b1,a2,b3,a4,'),
'cycle14': ("{% cycle one two as foo %}{% cycle foo %}", {'one': '1','two': '2'}, '12'), 'cycle14': ("{% cycle one two as foo %}{% cycle foo %}", {'one': '1', 'two': '2'}, '12'),
'cycle15': ("{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}", {'test': range(5), 'aye': 'a', 'bee': 'b'}, 'a0,b1,a2,b3,a4,'), 'cycle15': ("{% for i in test %}{% cycle aye bee %}{{ i }},{% endfor %}", {'test': range(5), 'aye': 'a', 'bee': 'b'}, 'a0,b1,a2,b3,a4,'),
'cycle16': ("{% cycle one|lower two as foo %}{% cycle foo %}", {'one': 'A','two': '2'}, 'a2'), 'cycle16': ("{% cycle one|lower two as foo %}{% cycle foo %}", {'one': 'A', 'two': '2'}, 'a2'),
'cycle17': ("{% cycle 'a' 'b' 'c' as abc silent %}{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, ""), 'cycle17': ("{% cycle 'a' 'b' 'c' as abc silent %}{% cycle abc %}{% cycle abc %}{% cycle abc %}{% cycle abc %}", {}, ""),
'cycle18': ("{% cycle 'a' 'b' 'c' as foo invalid_flag %}", {}, template.TemplateSyntaxError), 'cycle18': ("{% cycle 'a' 'b' 'c' as foo invalid_flag %}", {}, template.TemplateSyntaxError),
'cycle19': ("{% cycle 'a' 'b' as silent %}{% cycle silent %}", {}, "ab"), 'cycle19': ("{% cycle 'a' 'b' as silent %}{% cycle silent %}", {}, "ab"),
'cycle20': ("{% cycle one two as foo %} &amp; {% cycle foo %}", {'one' : 'A & B', 'two' : 'C & D'}, "A & B &amp; C & D"), 'cycle20': ("{% cycle one two as foo %} &amp; {% cycle foo %}", {'one' : 'A & B', 'two' : 'C & D'}, "A & B &amp; C & D"),
'cycle21': ("{% filter force_escape %}{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}", {'one' : 'A & B', 'two' : 'C & D'}, "A &amp; B &amp; C &amp; D"), 'cycle21': ("{% filter force_escape %}{% cycle one two as foo %} & {% cycle foo %}{% endfilter %}", {'one' : 'A & B', 'two' : 'C & D'}, "A &amp; B &amp; C &amp; D"),
'cycle22': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}", {'values': [1,2,3,4]}, "1234"), 'cycle22': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ x }}{% endfor %}", {'values': [1, 2, 3, 4]}, "1234"),
'cycle23': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}", {'values': [1,2,3,4]}, "a1b2c3a4"), 'cycle23': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{{ abc }}{{ x }}{% endfor %}", {'values': [1, 2, 3, 4]}, "a1b2c3a4"),
'included-cycle': ('{{ abc }}', {'abc': 'xxx'}, 'xxx'), 'included-cycle': ('{{ abc }}', {'abc': 'xxx'}, 'xxx'),
'cycle24': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}", {'values': [1,2,3,4]}, "abca"), 'cycle24': ("{% for x in values %}{% cycle 'a' 'b' 'c' as abc silent %}{% include 'included-cycle' %}{% endfor %}", {'values': [1, 2, 3, 4]}, "abca"),
'cycle25': ('{% cycle a as abc %}', {'a': '<'}, '<'), 'cycle25': ('{% cycle a as abc %}', {'a': '<'}, '<'),
'cycle26': ('{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}', {'a': '<', 'b': '>'}, '&lt;&gt;'), 'cycle26': ('{% load cycle from future %}{% cycle a b as ab %}{% cycle ab %}', {'a': '<', 'b': '>'}, '&lt;&gt;'),
@ -936,14 +936,14 @@ class TemplateTests(TransRealMixin, TestCase):
'filter06bis': ('{% filter upper|escape %}fail{% endfilter %}', {}, template.TemplateSyntaxError), 'filter06bis': ('{% filter upper|escape %}fail{% endfilter %}', {}, template.TemplateSyntaxError),
### FIRSTOF TAG ########################################################### ### FIRSTOF TAG ###########################################################
'firstof01': ('{% firstof a b c %}', {'a':0,'b':0,'c':0}, ''), 'firstof01': ('{% firstof a b c %}', {'a': 0, 'b': 0, 'c': 0}, ''),
'firstof02': ('{% firstof a b c %}', {'a':1,'b':0,'c':0}, '1'), 'firstof02': ('{% firstof a b c %}', {'a': 1, 'b': 0, 'c': 0}, '1'),
'firstof03': ('{% firstof a b c %}', {'a':0,'b':2,'c':0}, '2'), 'firstof03': ('{% firstof a b c %}', {'a': 0, 'b': 2, 'c': 0}, '2'),
'firstof04': ('{% firstof a b c %}', {'a':0,'b':0,'c':3}, '3'), 'firstof04': ('{% firstof a b c %}', {'a': 0, 'b': 0, 'c': 3}, '3'),
'firstof05': ('{% firstof a b c %}', {'a':1,'b':2,'c':3}, '1'), 'firstof05': ('{% firstof a b c %}', {'a': 1, 'b': 2, 'c': 3}, '1'),
'firstof06': ('{% firstof a b c %}', {'b':0,'c':3}, '3'), 'firstof06': ('{% firstof a b c %}', {'b': 0, 'c': 3}, '3'),
'firstof07': ('{% firstof a b "c" %}', {'a':0}, 'c'), 'firstof07': ('{% firstof a b "c" %}', {'a': 0}, 'c'),
'firstof08': ('{% firstof a b "c and d" %}', {'a':0,'b':0}, 'c and d'), 'firstof08': ('{% firstof a b "c and d" %}', {'a': 0, 'b': 0}, 'c and d'),
'firstof09': ('{% firstof %}', {}, template.TemplateSyntaxError), 'firstof09': ('{% firstof %}', {}, template.TemplateSyntaxError),
'firstof10': ('{% firstof a %}', {'a': '<'}, '<'), 'firstof10': ('{% firstof a %}', {'a': '<'}, '<'),
@ -1020,10 +1020,10 @@ class TemplateTests(TransRealMixin, TestCase):
'if-tag-lte-02': ("{% if 2 <= 1 %}yes{% else %}no{% endif %}", {}, "no"), 'if-tag-lte-02': ("{% if 2 <= 1 %}yes{% else %}no{% endif %}", {}, "no"),
# Contains # Contains
'if-tag-in-01': ("{% if 1 in x %}yes{% else %}no{% endif %}", {'x':[1]}, "yes"), 'if-tag-in-01': ("{% if 1 in x %}yes{% else %}no{% endif %}", {'x': [1]}, "yes"),
'if-tag-in-02': ("{% if 2 in x %}yes{% else %}no{% endif %}", {'x':[1]}, "no"), 'if-tag-in-02': ("{% if 2 in x %}yes{% else %}no{% endif %}", {'x': [1]}, "no"),
'if-tag-not-in-01': ("{% if 1 not in x %}yes{% else %}no{% endif %}", {'x':[1]}, "no"), 'if-tag-not-in-01': ("{% if 1 not in x %}yes{% else %}no{% endif %}", {'x': [1]}, "no"),
'if-tag-not-in-02': ("{% if 2 not in x %}yes{% else %}no{% endif %}", {'x':[1]}, "yes"), 'if-tag-not-in-02': ("{% if 2 not in x %}yes{% else %}no{% endif %}", {'x': [1]}, "yes"),
# AND # AND
'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'), 'if-tag-and01': ("{% if foo and bar %}yes{% else %}no{% endif %}", {'foo': True, 'bar': True}, 'yes'),
@ -1109,17 +1109,17 @@ class TemplateTests(TransRealMixin, TestCase):
'if-tag-shortcircuit02': ('{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}', {'x': TestObj()}, "no"), 'if-tag-shortcircuit02': ('{% if x.is_false and x.is_bad %}yes{% else %}no{% endif %}', {'x': TestObj()}, "no"),
# Non-existent args # Non-existent args
'if-tag-badarg01':("{% if x|default_if_none:y %}yes{% endif %}", {}, ''), 'if-tag-badarg01': ("{% if x|default_if_none:y %}yes{% endif %}", {}, ''),
'if-tag-badarg02':("{% if x|default_if_none:y %}yes{% endif %}", {'y': 0}, ''), 'if-tag-badarg02': ("{% if x|default_if_none:y %}yes{% endif %}", {'y': 0}, ''),
'if-tag-badarg03':("{% if x|default_if_none:y %}yes{% endif %}", {'y': 1}, 'yes'), 'if-tag-badarg03': ("{% if x|default_if_none:y %}yes{% endif %}", {'y': 1}, 'yes'),
'if-tag-badarg04':("{% if x|default_if_none:y %}yes{% else %}no{% endif %}", {}, 'no'), 'if-tag-badarg04': ("{% if x|default_if_none:y %}yes{% else %}no{% endif %}", {}, 'no'),
# Additional, more precise parsing tests are in SmartIfTests # Additional, more precise parsing tests are in SmartIfTests
### IFCHANGED TAG ######################################################### ### IFCHANGED TAG #########################################################
'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1,2,3)}, '123'), 'ifchanged01': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 2, 3)}, '123'),
'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1,1,3)}, '13'), 'ifchanged02': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 1, 3)}, '13'),
'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1,1,1)}, '1'), 'ifchanged03': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% endfor %}', {'num': (1, 1, 1)}, '1'),
'ifchanged04': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 2, 3), 'numx': (2, 2, 2)}, '122232'), 'ifchanged04': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 2, 3), 'numx': (2, 2, 2)}, '122232'),
'ifchanged05': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (1, 2, 3)}, '1123123123'), 'ifchanged05': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (1, 2, 3)}, '1123123123'),
'ifchanged06': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (2, 2, 2)}, '1222'), 'ifchanged06': ('{% for n in num %}{% ifchanged %}{{ n }}{% endifchanged %}{% for x in numx %}{% ifchanged %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 1), 'numx': (2, 2, 2)}, '1222'),
@ -1127,30 +1127,30 @@ class TemplateTests(TransRealMixin, TestCase):
'ifchanged08': ('{% for data in datalist %}{% for c,d in data %}{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}{% endif %}{% endfor %}{% endfor %}', {'datalist': [[(1, 'a'), (1, 'a'), (0, 'b'), (1, 'c')], [(0, 'a'), (1, 'c'), (1, 'd'), (1, 'd'), (0, 'e')]]}, 'accd'), 'ifchanged08': ('{% for data in datalist %}{% for c,d in data %}{% if c %}{% ifchanged %}{{ d }}{% endifchanged %}{% endif %}{% endfor %}{% endfor %}', {'datalist': [[(1, 'a'), (1, 'a'), (0, 'b'), (1, 'c')], [(0, 'a'), (1, 'c'), (1, 'd'), (1, 'd'), (0, 'e')]]}, 'accd'),
# Test one parameter given to ifchanged. # Test one parameter given to ifchanged.
'ifchanged-param01': ('{% for n in num %}{% ifchanged n %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1,2,3)}, '..1..2..3'), 'ifchanged-param01': ('{% for n in num %}{% ifchanged n %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1, 2, 3)}, '..1..2..3'),
'ifchanged-param02': ('{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}{{ x }}{% endfor %}{% endfor %}', {'num': (1,2,3), 'numx': (5,6,7)}, '..567..567..567'), 'ifchanged-param02': ('{% for n in num %}{% for x in numx %}{% ifchanged n %}..{% endifchanged %}{{ x }}{% endfor %}{% endfor %}', {'num': (1, 2, 3), 'numx': (5, 6, 7)}, '..567..567..567'),
# Test multiple parameters to ifchanged. # Test multiple parameters to ifchanged.
'ifchanged-param03': ('{% for n in num %}{{ n }}{% for x in numx %}{% ifchanged x n %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1,1,2), 'numx': (5,6,6)}, '156156256'), 'ifchanged-param03': ('{% for n in num %}{{ n }}{% for x in numx %}{% ifchanged x n %}{{ x }}{% endifchanged %}{% endfor %}{% endfor %}', {'num': (1, 1, 2), 'numx': (5, 6, 6)}, '156156256'),
# Test a date+hour like construct, where the hour of the last day # Test a date+hour like construct, where the hour of the last day
# is the same but the date had changed, so print the hour anyway. # is the same but the date had changed, so print the hour anyway.
'ifchanged-param04': ('{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},]}, '112323'), 'ifchanged-param04': ('{% for d in days %}{% ifchanged %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days': [{'day': 1, 'hours': [1, 2, 3]}, {'day': 2, 'hours': [3]}]}, '112323'),
# Logically the same as above, just written with explicit # Logically the same as above, just written with explicit
# ifchanged for the day. # ifchanged for the day.
'ifchanged-param05': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days':[{'day':1, 'hours':[1,2,3]},{'day':2, 'hours':[3]},]}, '112323'), 'ifchanged-param05': ('{% for d in days %}{% ifchanged d.day %}{{ d.day }}{% endifchanged %}{% for h in d.hours %}{% ifchanged d.day h %}{{ h }}{% endifchanged %}{% endfor %}{% endfor %}', {'days': [{'day': 1, 'hours': [1, 2, 3]}, {'day': 2, 'hours': [3]}]}, '112323'),
# Test the else clause of ifchanged. # Test the else clause of ifchanged.
'ifchanged-else01': ('{% for id in ids %}{{ id }}{% ifchanged id %}-first{% else %}-other{% endifchanged %},{% endfor %}', {'ids': [1,1,2,2,2,3]}, '1-first,1-other,2-first,2-other,2-other,3-first,'), 'ifchanged-else01': ('{% for id in ids %}{{ id }}{% ifchanged id %}-first{% else %}-other{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-first,1-other,2-first,2-other,2-other,3-first,'),
'ifchanged-else02': ('{% for id in ids %}{{ id }}-{% ifchanged id %}{% cycle red,blue %}{% else %}grey{% endifchanged %},{% endfor %}', {'ids': [1,1,2,2,2,3]}, '1-red,1-grey,2-blue,2-grey,2-grey,3-red,'), 'ifchanged-else02': ('{% for id in ids %}{{ id }}-{% ifchanged id %}{% cycle red,blue %}{% else %}grey{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-red,1-grey,2-blue,2-grey,2-grey,3-red,'),
'ifchanged-else03': ('{% for id in ids %}{{ id }}{% ifchanged id %}-{% cycle red,blue %}{% else %}{% endifchanged %},{% endfor %}', {'ids': [1,1,2,2,2,3]}, '1-red,1,2-blue,2,2,3-red,'), 'ifchanged-else03': ('{% for id in ids %}{{ id }}{% ifchanged id %}-{% cycle red,blue %}{% else %}{% endifchanged %},{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3]}, '1-red,1,2-blue,2,2,3-red,'),
'ifchanged-else04': ('{% for id in ids %}{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}{{ forloop.counter }}{% endfor %}', {'ids': [1,1,2,2,2,3,4]}, '***1*1...2***2*3...4...5***3*6***4*7'), 'ifchanged-else04': ('{% for id in ids %}{% ifchanged %}***{{ id }}*{% else %}...{% endifchanged %}{{ forloop.counter }}{% endfor %}', {'ids': [1, 1, 2, 2, 2, 3, 4]}, '***1*1...2***2*3...4...5***3*6***4*7'),
# Test whitespace in filter arguments # Test whitespace in filter arguments
'ifchanged-filter-ws': ('{% load custom %}{% for n in num %}{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1,2,3)}, '..1..2..3'), 'ifchanged-filter-ws': ('{% load custom %}{% for n in num %}{% ifchanged n|noop:"x y" %}..{% endifchanged %}{{ n }}{% endfor %}', {'num': (1, 2, 3)}, '..1..2..3'),
### IFEQUAL TAG ########################################################### ### IFEQUAL TAG ###########################################################
'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""), 'ifequal01': ("{% ifequal a b %}yes{% endifequal %}", {"a": 1, "b": 2}, ""),
@ -1501,8 +1501,8 @@ class TemplateTests(TransRealMixin, TestCase):
### HANDLING OF TEMPLATE_STRING_IF_INVALID ################################### ### HANDLING OF TEMPLATE_STRING_IF_INVALID ###################################
'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo','INVALID')), 'invalidstr01': ('{{ var|default:"Foo" }}', {}, ('Foo', 'INVALID')),
'invalidstr02': ('{{ var|default_if_none:"Foo" }}', {}, ('','INVALID')), 'invalidstr02': ('{{ var|default_if_none:"Foo" }}', {}, ('', 'INVALID')),
'invalidstr03': ('{% for v in var %}({{ v }}){% endfor %}', {}, ''), 'invalidstr03': ('{% for v in var %}({{ v }}){% endfor %}', {}, ''),
'invalidstr04': ('{% if var %}Yes{% else %}No{% endif %}', {}, 'No'), 'invalidstr04': ('{% if var %}Yes{% else %}No{% endif %}', {}, 'No'),
'invalidstr04_2': ('{% if var|default:"Foo" %}Yes{% else %}No{% endif %}', {}, 'Yes'), 'invalidstr04_2': ('{% if var|default:"Foo" %}Yes{% else %}No{% endif %}', {}, 'Yes'),
@ -1537,11 +1537,11 @@ class TemplateTests(TransRealMixin, TestCase):
'{{ item.foo }}' '{{ item.foo }}'
'{% endfor %},' '{% endfor %},'
'{% endfor %}', '{% endfor %}',
{'data': [{'foo':'c', 'bar':1}, {'data': [{'foo': 'c', 'bar': 1},
{'foo':'d', 'bar':1}, {'foo': 'd', 'bar': 1},
{'foo':'a', 'bar':2}, {'foo': 'a', 'bar': 2},
{'foo':'b', 'bar':2}, {'foo': 'b', 'bar': 2},
{'foo':'x', 'bar':3}]}, {'foo': 'x', 'bar': 3}]},
'1:cd,2:ab,3:x,'), '1:cd,2:ab,3:x,'),
# Test for silent failure when target variable isn't found # Test for silent failure when target variable isn't found
@ -1629,41 +1629,41 @@ class TemplateTests(TransRealMixin, TestCase):
'simpletag-renamed03': ('{% load custom %}{% minustwo_overridden_name 7 %}', {}, template.TemplateSyntaxError), 'simpletag-renamed03': ('{% load custom %}{% minustwo_overridden_name 7 %}', {}, template.TemplateSyntaxError),
### WIDTHRATIO TAG ######################################################## ### WIDTHRATIO TAG ########################################################
'widthratio01': ('{% widthratio a b 0 %}', {'a':50,'b':100}, '0'), 'widthratio01': ('{% widthratio a b 0 %}', {'a': 50, 'b': 100}, '0'),
'widthratio02': ('{% widthratio a b 100 %}', {'a':0,'b':0}, '0'), 'widthratio02': ('{% widthratio a b 100 %}', {'a': 0, 'b': 0}, '0'),
'widthratio03': ('{% widthratio a b 100 %}', {'a':0,'b':100}, '0'), 'widthratio03': ('{% widthratio a b 100 %}', {'a': 0, 'b': 100}, '0'),
'widthratio04': ('{% widthratio a b 100 %}', {'a':50,'b':100}, '50'), 'widthratio04': ('{% widthratio a b 100 %}', {'a': 50, 'b': 100}, '50'),
'widthratio05': ('{% widthratio a b 100 %}', {'a':100,'b':100}, '100'), 'widthratio05': ('{% widthratio a b 100 %}', {'a': 100, 'b': 100}, '100'),
# 62.5 should round to 63 on Python 2 and 62 on Python 3 # 62.5 should round to 63 on Python 2 and 62 on Python 3
# See http://docs.python.org/py3k/whatsnew/3.0.html # See http://docs.python.org/py3k/whatsnew/3.0.html
'widthratio06': ('{% widthratio a b 100 %}', {'a':50,'b':80}, '62' if six.PY3 else '63'), 'widthratio06': ('{% widthratio a b 100 %}', {'a': 50, 'b': 80}, '62' if six.PY3 else '63'),
# 71.4 should round to 71 # 71.4 should round to 71
'widthratio07': ('{% widthratio a b 100 %}', {'a':50,'b':70}, '71'), 'widthratio07': ('{% widthratio a b 100 %}', {'a': 50, 'b': 70}, '71'),
# Raise exception if we don't have 3 args, last one an integer # Raise exception if we don't have 3 args, last one an integer
'widthratio08': ('{% widthratio %}', {}, template.TemplateSyntaxError), 'widthratio08': ('{% widthratio %}', {}, template.TemplateSyntaxError),
'widthratio09': ('{% widthratio a b %}', {'a':50,'b':100}, template.TemplateSyntaxError), 'widthratio09': ('{% widthratio a b %}', {'a': 50, 'b': 100}, template.TemplateSyntaxError),
'widthratio10': ('{% widthratio a b 100.0 %}', {'a':50,'b':100}, '50'), 'widthratio10': ('{% widthratio a b 100.0 %}', {'a': 50, 'b': 100}, '50'),
# #10043: widthratio should allow max_width to be a variable # #10043: widthratio should allow max_width to be a variable
'widthratio11': ('{% widthratio a b c %}', {'a':50,'b':100, 'c': 100}, '50'), 'widthratio11': ('{% widthratio a b c %}', {'a': 50, 'b': 100, 'c': 100}, '50'),
# #18739: widthratio should handle None args consistently with non-numerics # #18739: widthratio should handle None args consistently with non-numerics
'widthratio12a': ('{% widthratio a b c %}', {'a':'a','b':100,'c':100}, ''), 'widthratio12a': ('{% widthratio a b c %}', {'a': 'a', 'b': 100, 'c': 100}, ''),
'widthratio12b': ('{% widthratio a b c %}', {'a':None,'b':100,'c':100}, ''), 'widthratio12b': ('{% widthratio a b c %}', {'a': None, 'b': 100, 'c': 100}, ''),
'widthratio13a': ('{% widthratio a b c %}', {'a':0,'b':'b','c':100}, ''), 'widthratio13a': ('{% widthratio a b c %}', {'a': 0, 'b': 'b', 'c': 100}, ''),
'widthratio13b': ('{% widthratio a b c %}', {'a':0,'b':None,'c':100}, ''), 'widthratio13b': ('{% widthratio a b c %}', {'a': 0, 'b': None, 'c': 100}, ''),
'widthratio14a': ('{% widthratio a b c %}', {'a':0,'b':100,'c':'c'}, template.TemplateSyntaxError), 'widthratio14a': ('{% widthratio a b c %}', {'a': 0, 'b': 100, 'c': 'c'}, template.TemplateSyntaxError),
'widthratio14b': ('{% widthratio a b c %}', {'a':0,'b':100,'c':None}, template.TemplateSyntaxError), 'widthratio14b': ('{% widthratio a b c %}', {'a': 0, 'b': 100, 'c': None}, template.TemplateSyntaxError),
# Test whitespace in filter argument # Test whitespace in filter argument
'widthratio15': ('{% load custom %}{% widthratio a|noop:"x y" b 0 %}', {'a':50,'b':100}, '0'), 'widthratio15': ('{% load custom %}{% widthratio a|noop:"x y" b 0 %}', {'a': 50, 'b': 100}, '0'),
# Widthratio with variable assignment # Widthratio with variable assignment
'widthratio16': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a':50,'b':100}, '-50-'), 'widthratio16': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a': 50, 'b': 100}, '-50-'),
'widthratio17': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a':100,'b':100}, '-100-'), 'widthratio17': ('{% widthratio a b 100 as variable %}-{{ variable }}-', {'a': 100, 'b': 100}, '-100-'),
'widthratio18': ('{% widthratio a b 100 as %}', {}, template.TemplateSyntaxError), 'widthratio18': ('{% widthratio a b 100 as %}', {}, template.TemplateSyntaxError),
'widthratio19': ('{% widthratio a b 100 not_as variable %}', {}, template.TemplateSyntaxError), 'widthratio19': ('{% widthratio a b 100 not_as variable %}', {}, template.TemplateSyntaxError),
@ -1712,8 +1712,8 @@ class TemplateTests(TransRealMixin, TestCase):
'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'), 'url10': ('{% url "template_tests.views.client_action" id=client.id action="two words" %}', {'client': {'id': 1}}, '/url_tag/client/1/two%20words/'),
'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/%3D%3D/'), 'url11': ('{% url "template_tests.views.client_action" id=client.id action="==" %}', {'client': {'id': 1}}, '/url_tag/client/1/%3D%3D/'),
'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/client/1/%2C/'), 'url12': ('{% url "template_tests.views.client_action" id=client.id action="," %}', {'client': {'id': 1}}, '/url_tag/client/1/%2C/'),
'url13': ('{% url "template_tests.views.client_action" id=client.id action=arg|join:"-" %}', {'client': {'id': 1}, 'arg':['a','b']}, '/url_tag/client/1/a-b/'), 'url13': ('{% url "template_tests.views.client_action" id=client.id action=arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'),
'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg':['a','b']}, '/url_tag/client/1/a-b/'), 'url14': ('{% url "template_tests.views.client_action" client.id arg|join:"-" %}', {'client': {'id': 1}, 'arg': ['a', 'b']}, '/url_tag/client/1/a-b/'),
'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/url_tag/client/12/test/'), 'url15': ('{% url "template_tests.views.client_action" 12 "test" %}', {}, '/url_tag/client/12/test/'),
'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/url_tag/client/1%2C2/'), 'url18': ('{% url "template_tests.views.client" "1,2" %}', {}, '/url_tag/client/1%2C2/'),
@ -1809,7 +1809,7 @@ class TemplateTests(TransRealMixin, TestCase):
'autoescape-filters02': ('{{ var|join:" & \" }}', {"var": ("Tom", "Dick", "Harry")}, "Tom & Dick & Harry"), 'autoescape-filters02': ('{{ var|join:" & \" }}', {"var": ("Tom", "Dick", "Harry")}, "Tom & Dick & Harry"),
# Literal strings are safe. # Literal strings are safe.
'autoescape-literals01': ('{{ "this & that" }}',{}, "this & that"), 'autoescape-literals01': ('{{ "this & that" }}', {}, "this & that"),
# Iterating over strings outputs safe characters. # Iterating over strings outputs safe characters.
'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&amp;,R,"), 'autoescape-stringiterations01': ('{% for l in var %}{{ l }},{% endfor %}', {'var': 'K&R'}, "K,&amp;,R,"),

View File

@ -147,12 +147,12 @@ class ClientTest(TestCase):
def test_redirect_http(self): def test_redirect_http(self):
"GET a URL that redirects to an http URI" "GET a URL that redirects to an http URI"
response = self.client.get('/test_client/http_redirect_view/',follow=True) response = self.client.get('/test_client/http_redirect_view/', follow=True)
self.assertFalse(response.test_was_secure_request) self.assertFalse(response.test_was_secure_request)
def test_redirect_https(self): def test_redirect_https(self):
"GET a URL that redirects to an https URI" "GET a URL that redirects to an https URI"
response = self.client.get('/test_client/https_redirect_view/',follow=True) response = self.client.get('/test_client/https_redirect_view/', follow=True)
self.assertTrue(response.test_was_secure_request) self.assertTrue(response.test_was_secure_request)
def test_notfound_response(self): def test_notfound_response(self):
@ -169,7 +169,7 @@ class ClientTest(TestCase):
'email': 'foo@example.com', 'email': 'foo@example.com',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -179,7 +179,7 @@ class ClientTest(TestCase):
"GET a form, providing hints in the GET data" "GET a form, providing hints in the GET data"
hints = { hints = {
'text': 'Hello World', 'text': 'Hello World',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.get('/test_client/form_view/', data=hints) response = self.client.get('/test_client/form_view/', data=hints)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -209,7 +209,7 @@ class ClientTest(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -224,7 +224,7 @@ class ClientTest(TestCase):
'email': 'foo@example.com', 'email': 'foo@example.com',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK') self.assertContains(response, 'POST data OK')
@ -255,7 +255,7 @@ class ClientTest(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data has errors') self.assertContains(response, 'POST data has errors')

View File

@ -254,7 +254,7 @@ def mass_mail_sending_view(request):
['second@example.com', 'third@example.com']) ['second@example.com', 'third@example.com'])
c = mail.get_connection() c = mail.get_connection()
c.send_messages([m1,m2]) c.send_messages([m1, m2])
return HttpResponse("Mail sent") return HttpResponse("Mail sent")

View File

@ -237,7 +237,7 @@ class AssertTemplateUsedTests(TestCase):
'email': 'foo@example.com', 'email': 'foo@example.com',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view_with_template/', post_data) response = self.client.post('/test_client/form_view_with_template/', post_data)
self.assertContains(response, 'POST data OK') self.assertContains(response, 'POST data OK')
@ -439,7 +439,7 @@ class AssertFormErrorTests(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -461,7 +461,7 @@ class AssertFormErrorTests(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -483,7 +483,7 @@ class AssertFormErrorTests(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -505,7 +505,7 @@ class AssertFormErrorTests(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -530,7 +530,7 @@ class AssertFormErrorTests(TestCase):
'email': 'not an email address', 'email': 'not an email address',
'value': 37, 'value': 37,
'single': 'b', 'single': 'b',
'multi': ('b','c','e') 'multi': ('b', 'c', 'e')
} }
response = self.client.post('/test_client/form_view/', post_data) response = self.client.post('/test_client/form_view/', post_data)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@ -558,12 +558,12 @@ class AssertFormsetErrorTests(TestCase):
'form-0-email': 'not an email address', 'form-0-email': 'not an email address',
'form-0-value': 37, 'form-0-value': 37,
'form-0-single': 'b', 'form-0-single': 'b',
'form-0-multi': ('b','c','e'), 'form-0-multi': ('b', 'c', 'e'),
'form-1-text': 'Hello World', 'form-1-text': 'Hello World',
'form-1-email': 'email@domain.com', 'form-1-email': 'email@domain.com',
'form-1-value': 37, 'form-1-value': 37,
'form-1-single': 'b', 'form-1-single': 'b',
'form-1-multi': ('b','c','e'), 'form-1-multi': ('b', 'c', 'e'),
}) })
# For testing non-form errors # For testing non-form errors
self.response_nonform_errors = self.getResponse({ self.response_nonform_errors = self.getResponse({
@ -573,12 +573,12 @@ class AssertFormsetErrorTests(TestCase):
'form-0-email': 'email@domain.com', 'form-0-email': 'email@domain.com',
'form-0-value': 37, 'form-0-value': 37,
'form-0-single': 'b', 'form-0-single': 'b',
'form-0-multi': ('b','c','e'), 'form-0-multi': ('b', 'c', 'e'),
'form-1-text': 'Hello World', 'form-1-text': 'Hello World',
'form-1-email': 'email@domain.com', 'form-1-email': 'email@domain.com',
'form-1-value': 37, 'form-1-value': 37,
'form-1-single': 'b', 'form-1-single': 'b',
'form-1-multi': ('b','c','e'), 'form-1-multi': ('b', 'c', 'e'),
}) })
def getResponse(self, post_data): def getResponse(self, post_data):
@ -808,7 +808,7 @@ class ExceptionTests(TestCase):
def test_exception_cleared(self): def test_exception_cleared(self):
"#5836 - A stale user exception isn't re-raised by the test client." "#5836 - A stale user exception isn't re-raised by the test client."
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
try: try:
self.client.get("/test_client_regress/staff_only/") self.client.get("/test_client_regress/staff_only/")
@ -871,7 +871,7 @@ class ContextTests(TestCase):
def test_single_context(self): def test_single_context(self):
"Context variables can be retrieved from a single context" "Context variables can be retrieved from a single context"
response = self.client.get("/test_client_regress/request_data/", data={'foo':'whiz'}) response = self.client.get("/test_client_regress/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, Context) self.assertEqual(response.context.__class__, Context)
self.assertTrue('get-foo' in response.context) self.assertTrue('get-foo' in response.context)
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
@ -886,7 +886,7 @@ class ContextTests(TestCase):
def test_inherited_context(self): def test_inherited_context(self):
"Context variables can be retrieved from a list of contexts" "Context variables can be retrieved from a list of contexts"
response = self.client.get("/test_client_regress/request_data_extended/", data={'foo':'whiz'}) response = self.client.get("/test_client_regress/request_data_extended/", data={'foo': 'whiz'})
self.assertEqual(response.context.__class__, ContextList) self.assertEqual(response.context.__class__, ContextList)
self.assertEqual(len(response.context), 2) self.assertEqual(len(response.context), 2)
self.assertTrue('get-foo' in response.context) self.assertTrue('get-foo' in response.context)
@ -957,7 +957,7 @@ class SessionTests(TestCase):
self.assertEqual(response.content, b'YES') self.assertEqual(response.content, b'YES')
# Log in # Log in
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
# Session should still contain the modified value # Session should still contain the modified value
@ -968,7 +968,7 @@ class SessionTests(TestCase):
def test_logout(self): def test_logout(self):
"""Logout should work whether the user is logged in or not (#9978).""" """Logout should work whether the user is logged in or not (#9978)."""
self.client.logout() self.client.logout()
login = self.client.login(username='testclient',password='password') login = self.client.login(username='testclient', password='password')
self.assertTrue(login, 'Could not log in') self.assertTrue(login, 'Could not log in')
self.client.logout() self.client.logout()
self.client.logout() self.client.logout()
@ -1120,7 +1120,7 @@ class QueryStringTests(TestCase):
for method_name in ('get', 'head'): for method_name in ('get', 'head'):
# A GET-like request can pass a query string as data # A GET-like request can pass a query string as data
method = getattr(self.client, method_name) method = getattr(self.client, method_name)
response = method("/test_client_regress/request_data/", data={'foo':'whiz'}) response = method("/test_client_regress/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
@ -1130,11 +1130,11 @@ class QueryStringTests(TestCase):
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
# Data provided in the URL to a GET-like request is overridden by actual form data # Data provided in the URL to a GET-like request is overridden by actual form data
response = method("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'}) response = method("/test_client_regress/request_data/?foo=whiz", data={'foo': 'bang'})
self.assertEqual(response.context['get-foo'], 'bang') self.assertEqual(response.context['get-foo'], 'bang')
self.assertEqual(response.context['request-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang')
response = method("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'}) response = method("/test_client_regress/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['get-foo'], None)
self.assertEqual(response.context['get-bar'], 'bang') self.assertEqual(response.context['get-bar'], 'bang')
self.assertEqual(response.context['request-foo'], None) self.assertEqual(response.context['request-foo'], None)
@ -1142,7 +1142,7 @@ class QueryStringTests(TestCase):
def test_post_like_requests(self): def test_post_like_requests(self):
# A POST-like request can pass a query string as data # A POST-like request can pass a query string as data
response = self.client.post("/test_client_regress/request_data/", data={'foo':'whiz'}) response = self.client.post("/test_client_regress/request_data/", data={'foo': 'whiz'})
self.assertEqual(response.context['get-foo'], None) self.assertEqual(response.context['get-foo'], None)
self.assertEqual(response.context['post-foo'], 'whiz') self.assertEqual(response.context['post-foo'], 'whiz')
@ -1153,12 +1153,12 @@ class QueryStringTests(TestCase):
self.assertEqual(response.context['request-foo'], 'whiz') self.assertEqual(response.context['request-foo'], 'whiz')
# POST data provided in the URL augments actual form data # POST data provided in the URL augments actual form data
response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'}) response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'foo': 'bang'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['post-foo'], 'bang') self.assertEqual(response.context['post-foo'], 'bang')
self.assertEqual(response.context['request-foo'], 'bang') self.assertEqual(response.context['request-foo'], 'bang')
response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'}) response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'bar': 'bang'})
self.assertEqual(response.context['get-foo'], 'whiz') self.assertEqual(response.context['get-foo'], 'whiz')
self.assertEqual(response.context['get-bar'], None) self.assertEqual(response.context['get-bar'], None)
self.assertEqual(response.context['post-foo'], None) self.assertEqual(response.context['post-foo'], None)

View File

@ -9,7 +9,7 @@ urlpatterns = patterns('',
(r'^staff_only/$', views.staff_only_view), (r'^staff_only/$', views.staff_only_view),
(r'^get_view/$', views.get_view), (r'^get_view/$', views.get_view),
(r'^request_data/$', views.request_data), (r'^request_data/$', views.request_data),
(r'^request_data_extended/$', views.request_data, {'template':'extended.html', 'data':'bacon'}), (r'^request_data_extended/$', views.request_data, {'template': 'extended.html', 'data': 'bacon'}),
url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'), url(r'^arg_view/(?P<name>.+)/$', views.view_with_argument, name='arg_view'),
url(r'^nested_view/$', views.nested_view, name='nested_view'), url(r'^nested_view/$', views.nested_view, name='nested_view'),
(r'^login_protected_redirect_view/$', views.login_protected_redirect_view), (r'^login_protected_redirect_view/$', views.login_protected_redirect_view),

View File

@ -69,7 +69,7 @@ def nested_view(request):
setup_test_environment() setup_test_environment()
c = Client() c = Client()
c.get("/test_client_regress/no_template_view") c.get("/test_client_regress/no_template_view")
return render_to_response('base.html', {'nested':'yes'}) return render_to_response('base.html', {'nested': 'yes'})
def login_protected_redirect_view(request): def login_protected_redirect_view(request):
"A view that redirects all requests to the GET view" "A view that redirects all requests to the GET view"

View File

@ -37,7 +37,7 @@ class DependencyOrderingTests(unittest.TestCase):
} }
ordered = runner.dependency_ordered(raw, dependencies=dependencies) ordered = runner.dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig,value in ordered] ordered_sigs = [sig for sig, value in ordered]
self.assertIn('s1', ordered_sigs) self.assertIn('s1', ordered_sigs)
self.assertIn('s2', ordered_sigs) self.assertIn('s2', ordered_sigs)
@ -57,7 +57,7 @@ class DependencyOrderingTests(unittest.TestCase):
} }
ordered = runner.dependency_ordered(raw, dependencies=dependencies) ordered = runner.dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig,value in ordered] ordered_sigs = [sig for sig, value in ordered]
self.assertIn('s1', ordered_sigs) self.assertIn('s1', ordered_sigs)
self.assertIn('s2', ordered_sigs) self.assertIn('s2', ordered_sigs)
@ -78,13 +78,13 @@ class DependencyOrderingTests(unittest.TestCase):
('s4', ('s4_db', ['delta'])), ('s4', ('s4_db', ['delta'])),
] ]
dependencies = { dependencies = {
'alpha': ['bravo','delta'], 'alpha': ['bravo', 'delta'],
'bravo': ['charlie'], 'bravo': ['charlie'],
'delta': ['charlie'], 'delta': ['charlie'],
} }
ordered = runner.dependency_ordered(raw, dependencies=dependencies) ordered = runner.dependency_ordered(raw, dependencies=dependencies)
ordered_sigs = [sig for sig,aliases in ordered] ordered_sigs = [sig for sig, aliases in ordered]
self.assertIn('s1', ordered_sigs) self.assertIn('s1', ordered_sigs)
self.assertIn('s2', ordered_sigs) self.assertIn('s2', ordered_sigs)
@ -158,9 +158,9 @@ class ManageCommandTests(unittest.TestCase):
class CustomOptionsTestRunner(runner.DiscoverRunner): class CustomOptionsTestRunner(runner.DiscoverRunner):
option_list = ( option_list = (
make_option('--option_a','-a', action='store', dest='option_a', default='1'), make_option('--option_a', '-a', action='store', dest='option_a', default='1'),
make_option('--option_b','-b', action='store', dest='option_b', default='2'), make_option('--option_b', '-b', action='store', dest='option_b', default='2'),
make_option('--option_c','-c', action='store', dest='option_c', default='3'), make_option('--option_c', '-c', action='store', dest='option_c', default='3'),
) )
def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs): def __init__(self, verbosity=1, interactive=True, failfast=True, option_a=None, option_b=None, option_c=None, **kwargs):

View File

@ -128,7 +128,7 @@ class UpdateOnlyFieldsTests(TestCase):
a1 = Account.objects.create(num=1) a1 = Account.objects.create(num=1)
a2 = Account.objects.create(num=2) a2 = Account.objects.create(num=2)
e1.accounts = [a1,a2] e1.accounts = [a1, a2]
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
e1.save(update_fields=['accounts']) e1.save(update_fields=['accounts'])

View File

@ -37,8 +37,8 @@ resolve_test_data = (
('/unnamed/view_class/42/37/', 'urlpatterns_reverse.views.ViewClass', None, '', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}), ('/unnamed/view_class/42/37/', 'urlpatterns_reverse.views.ViewClass', None, '', views.view_class_instance, tuple(), {'arg1': '42', 'arg2': '37'}),
# If you have no kwargs, you get an args list. # If you have no kwargs, you get an args list.
('/no_kwargs/42/37/', 'no-kwargs', None, '', views.empty_view, ('42','37'), {}), ('/no_kwargs/42/37/', 'no-kwargs', None, '', views.empty_view, ('42', '37'), {}),
('/included/no_kwargs/42/37/', 'inc-no-kwargs', None, '', views.empty_view, ('42','37'), {}), ('/included/no_kwargs/42/37/', 'inc-no-kwargs', None, '', views.empty_view, ('42', '37'), {}),
# Namespaces # Namespaces
('/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}), ('/test1/inner/42/37/', 'urlobject-view', 'testapp', 'test-ns1', 'empty_view', tuple(), {'arg1': '42', 'arg2': '37'}),
@ -55,7 +55,7 @@ resolve_test_data = (
# Namespaces capturing variables # Namespaces capturing variables
('/inc70/', 'inner-nothing', None, 'inc-ns5', views.empty_view, tuple(), {'outer': '70'}), ('/inc70/', 'inner-nothing', None, 'inc-ns5', views.empty_view, tuple(), {'outer': '70'}),
('/inc78/extra/foobar/', 'inner-extra', None, 'inc-ns5', views.empty_view, tuple(), {'outer':'78', 'extra':'foobar'}), ('/inc78/extra/foobar/', 'inner-extra', None, 'inc-ns5', views.empty_view, tuple(), {'outer': '78', 'extra': 'foobar'}),
) )
test_data = ( test_data = (
@ -137,9 +137,9 @@ test_data = (
# the method. This is potentially ambiguous, as you have to pick the # the method. This is potentially ambiguous, as you have to pick the
# correct view for the arguments provided. # correct view for the arguments provided.
('kwargs_view', '/arg_view/', [], {}), ('kwargs_view', '/arg_view/', [], {}),
('kwargs_view', '/arg_view/10/', [], {'arg1':10}), ('kwargs_view', '/arg_view/10/', [], {'arg1': 10}),
('urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/', [], {}), ('urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/', [], {}),
('urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/10/', [], {'arg1':10}), ('urlpatterns_reverse.views.absolute_kwargs_view', '/absolute_arg_view/10/', [], {'arg1': 10}),
('non_path_include', '/includes/non_path_include/', [], {}), ('non_path_include', '/includes/non_path_include/', [], {}),
# Tests for #13154 # Tests for #13154
@ -343,14 +343,14 @@ class NamespaceTests(TestCase):
def test_ambiguous_object(self): def test_ambiguous_object(self):
"Names deployed via dynamic URL objects that require namespaces can't be resolved" "Names deployed via dynamic URL objects that require namespaces can't be resolved"
self.assertRaises(NoReverseMatch, reverse, 'urlobject-view') self.assertRaises(NoReverseMatch, reverse, 'urlobject-view')
self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', args=[37, 42])
self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1':42, 'arg2':37}) self.assertRaises(NoReverseMatch, reverse, 'urlobject-view', kwargs={'arg1': 42, 'arg2': 37})
def test_ambiguous_urlpattern(self): def test_ambiguous_urlpattern(self):
"Names deployed via dynamic URL objects that require namespaces can't be resolved" "Names deployed via dynamic URL objects that require namespaces can't be resolved"
self.assertRaises(NoReverseMatch, reverse, 'inner-nothing') self.assertRaises(NoReverseMatch, reverse, 'inner-nothing')
self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37,42]) self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', args=[37, 42])
self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1':42, 'arg2':37}) self.assertRaises(NoReverseMatch, reverse, 'inner-nothing', kwargs={'arg1': 42, 'arg2': 37})
def test_non_existent_namespace(self): def test_non_existent_namespace(self):
"Non-existent namespaces raise errors" "Non-existent namespaces raise errors"
@ -360,99 +360,99 @@ class NamespaceTests(TestCase):
def test_normal_name(self): def test_normal_name(self):
"Normal lookups work as expected" "Normal lookups work as expected"
self.assertEqual('/normal/', reverse('normal-view')) self.assertEqual('/normal/', reverse('normal-view'))
self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37,42])) self.assertEqual('/normal/37/42/', reverse('normal-view', args=[37, 42]))
self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/normal/42/37/', reverse('normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/+%5C$*/', reverse('special-view')) self.assertEqual('/+%5C$*/', reverse('special-view'))
def test_simple_included_name(self): def test_simple_included_name(self):
"Normal lookups work on names included from other patterns" "Normal lookups work on names included from other patterns"
self.assertEqual('/included/normal/', reverse('inc-normal-view')) self.assertEqual('/included/normal/', reverse('inc-normal-view'))
self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37,42])) self.assertEqual('/included/normal/37/42/', reverse('inc-normal-view', args=[37, 42]))
self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/included/normal/42/37/', reverse('inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/included/+%5C$*/', reverse('inc-special-view')) self.assertEqual('/included/+%5C$*/', reverse('inc-special-view'))
def test_namespace_object(self): def test_namespace_object(self):
"Dynamic URL objects can be found using a namespace" "Dynamic URL objects can be found using a namespace"
self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view')) self.assertEqual('/test1/inner/', reverse('test-ns1:urlobject-view'))
self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37,42])) self.assertEqual('/test1/inner/37/42/', reverse('test-ns1:urlobject-view', args=[37, 42]))
self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/test1/inner/42/37/', reverse('test-ns1:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/test1/inner/+%5C$*/', reverse('test-ns1:urlobject-special-view')) self.assertEqual('/test1/inner/+%5C$*/', reverse('test-ns1:urlobject-special-view'))
def test_embedded_namespace_object(self): def test_embedded_namespace_object(self):
"Namespaces can be installed anywhere in the URL pattern tree" "Namespaces can be installed anywhere in the URL pattern tree"
self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view')) self.assertEqual('/included/test3/inner/', reverse('test-ns3:urlobject-view'))
self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/included/test3/inner/37/42/', reverse('test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/included/test3/inner/42/37/', reverse('test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/included/test3/inner/+%5C$*/', reverse('test-ns3:urlobject-special-view')) self.assertEqual('/included/test3/inner/+%5C$*/', reverse('test-ns3:urlobject-special-view'))
def test_namespace_pattern(self): def test_namespace_pattern(self):
"Namespaces can be applied to include()'d urlpatterns" "Namespaces can be applied to include()'d urlpatterns"
self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view')) self.assertEqual('/ns-included1/normal/', reverse('inc-ns1:inc-normal-view'))
self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37,42])) self.assertEqual('/ns-included1/normal/37/42/', reverse('inc-ns1:inc-normal-view', args=[37, 42]))
self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/ns-included1/normal/42/37/', reverse('inc-ns1:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/ns-included1/+%5C$*/', reverse('inc-ns1:inc-special-view')) self.assertEqual('/ns-included1/+%5C$*/', reverse('inc-ns1:inc-special-view'))
def test_namespace_pattern_with_variable_prefix(self): def test_namespace_pattern_with_variable_prefix(self):
"When using a include with namespaces when there is a regex variable in front of it" "When using a include with namespaces when there is a regex variable in front of it"
self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', kwargs={'outer':42})) self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', kwargs={'outer': 42}))
self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', args=[42])) self.assertEqual('/ns-outer/42/normal/', reverse('inc-outer:inc-normal-view', args=[42]))
self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', kwargs={'outer':42, 'arg1': 37, 'arg2': 4})) self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', kwargs={'outer': 42, 'arg1': 37, 'arg2': 4}))
self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', args=[42, 37, 4])) self.assertEqual('/ns-outer/42/normal/37/4/', reverse('inc-outer:inc-normal-view', args=[42, 37, 4]))
self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', kwargs={'outer':42})) self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', kwargs={'outer': 42}))
self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', args=[42])) self.assertEqual('/ns-outer/42/+%5C$*/', reverse('inc-outer:inc-special-view', args=[42]))
def test_multiple_namespace_pattern(self): def test_multiple_namespace_pattern(self):
"Namespaces can be embedded" "Namespaces can be embedded"
self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view')) self.assertEqual('/ns-included1/test3/inner/', reverse('inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/ns-included1/test3/inner/37/42/', reverse('inc-ns1:test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/ns-included1/test3/inner/42/37/', reverse('inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:test-ns3:urlobject-special-view')) self.assertEqual('/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:test-ns3:urlobject-special-view'))
def test_nested_namespace_pattern(self): def test_nested_namespace_pattern(self):
"Namespaces can be nested" "Namespaces can be nested"
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view')) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view'))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37,42])) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/37/42/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', args=[37, 42]))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/42/37/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view')) self.assertEqual('/ns-included1/ns-included4/ns-included1/test3/inner/+%5C$*/', reverse('inc-ns1:inc-ns4:inc-ns1:test-ns3:urlobject-special-view'))
def test_app_lookup_object(self): def test_app_lookup_object(self):
"A default application namespace can be used for lookup" "A default application namespace can be used for lookup"
self.assertEqual('/default/inner/', reverse('testapp:urlobject-view')) self.assertEqual('/default/inner/', reverse('testapp:urlobject-view'))
self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42])) self.assertEqual('/default/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42]))
self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/default/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/default/inner/+%5C$*/', reverse('testapp:urlobject-special-view')) self.assertEqual('/default/inner/+%5C$*/', reverse('testapp:urlobject-special-view'))
def test_app_lookup_object_with_default(self): def test_app_lookup_object_with_default(self):
"A default application namespace is sensitive to the 'current' app can be used for lookup" "A default application namespace is sensitive to the 'current' app can be used for lookup"
self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3')) self.assertEqual('/included/test3/inner/', reverse('testapp:urlobject-view', current_app='test-ns3'))
self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37,42], current_app='test-ns3')) self.assertEqual('/included/test3/inner/37/42/', reverse('testapp:urlobject-view', args=[37, 42], current_app='test-ns3'))
self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='test-ns3')) self.assertEqual('/included/test3/inner/42/37/', reverse('testapp:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='test-ns3'))
self.assertEqual('/included/test3/inner/+%5C$*/', reverse('testapp:urlobject-special-view', current_app='test-ns3')) self.assertEqual('/included/test3/inner/+%5C$*/', reverse('testapp:urlobject-special-view', current_app='test-ns3'))
def test_app_lookup_object_without_default(self): def test_app_lookup_object_without_default(self):
"An application namespace without a default is sensitive to the 'current' app can be used for lookup" "An application namespace without a default is sensitive to the 'current' app can be used for lookup"
self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view')) self.assertEqual('/other2/inner/', reverse('nodefault:urlobject-view'))
self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42])) self.assertEqual('/other2/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42]))
self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/other2/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/other2/inner/+%5C$*/', reverse('nodefault:urlobject-special-view')) self.assertEqual('/other2/inner/+%5C$*/', reverse('nodefault:urlobject-special-view'))
self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1')) self.assertEqual('/other1/inner/', reverse('nodefault:urlobject-view', current_app='other-ns1'))
self.assertEqual('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37,42], current_app='other-ns1')) self.assertEqual('/other1/inner/37/42/', reverse('nodefault:urlobject-view', args=[37, 42], current_app='other-ns1'))
self.assertEqual('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1':42, 'arg2':37}, current_app='other-ns1')) self.assertEqual('/other1/inner/42/37/', reverse('nodefault:urlobject-view', kwargs={'arg1': 42, 'arg2': 37}, current_app='other-ns1'))
self.assertEqual('/other1/inner/+%5C$*/', reverse('nodefault:urlobject-special-view', current_app='other-ns1')) self.assertEqual('/other1/inner/+%5C$*/', reverse('nodefault:urlobject-special-view', current_app='other-ns1'))
def test_special_chars_namespace(self): def test_special_chars_namespace(self):
self.assertEqual('/+%5C$*/included/normal/', reverse('special:inc-normal-view')) self.assertEqual('/+%5C$*/included/normal/', reverse('special:inc-normal-view'))
self.assertEqual('/+%5C$*/included/normal/37/42/', reverse('special:inc-normal-view', args=[37,42])) self.assertEqual('/+%5C$*/included/normal/37/42/', reverse('special:inc-normal-view', args=[37, 42]))
self.assertEqual('/+%5C$*/included/normal/42/37/', reverse('special:inc-normal-view', kwargs={'arg1':42, 'arg2':37})) self.assertEqual('/+%5C$*/included/normal/42/37/', reverse('special:inc-normal-view', kwargs={'arg1': 42, 'arg2': 37}))
self.assertEqual('/+%5C$*/included/+%5C$*/', reverse('special:inc-special-view')) self.assertEqual('/+%5C$*/included/+%5C$*/', reverse('special:inc-special-view'))
def test_namespaces_with_variables(self): def test_namespaces_with_variables(self):
"Namespace prefixes can capture variables: see #15900" "Namespace prefixes can capture variables: see #15900"
self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', kwargs={'outer': '70'})) self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', kwargs={'outer': '70'}))
self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', kwargs={'outer':'78', 'extra':'foobar'})) self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', kwargs={'outer': '78', 'extra': 'foobar'}))
self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', args=['70'])) self.assertEqual('/inc70/', reverse('inc-ns5:inner-nothing', args=['70']))
self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78','foobar'])) self.assertEqual('/inc78/extra/foobar/', reverse('inc-ns5:inner-extra', args=['78', 'foobar']))
@override_settings(ROOT_URLCONF = urlconf_outer.__name__) @override_settings(ROOT_URLCONF = urlconf_outer.__name__)

View File

@ -139,14 +139,14 @@ class SortedDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
class MergeDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase): class MergeDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
def test_simple_mergedict(self): def test_simple_mergedict(self):
d1 = {'chris':'cool', 'camri':'cute', 'cotton':'adorable', d1 = {'chris': 'cool', 'camri': 'cute', 'cotton': 'adorable',
'tulip':'snuggable', 'twoofme':'firstone'} 'tulip': 'snuggable', 'twoofme': 'firstone'}
d2 = {'chris2':'cool2', 'camri2':'cute2', 'cotton2':'adorable2', d2 = {'chris2': 'cool2', 'camri2': 'cute2', 'cotton2': 'adorable2',
'tulip2':'snuggable2'} 'tulip2': 'snuggable2'}
d3 = {'chris3':'cool3', 'camri3':'cute3', 'cotton3':'adorable3', d3 = {'chris3': 'cool3', 'camri3': 'cute3', 'cotton3': 'adorable3',
'tulip3':'snuggable3'} 'tulip3': 'snuggable3'}
md = MergeDict(d1, d2, d3) md = MergeDict(d1, d2, d3)
@ -183,7 +183,7 @@ class MergeDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
[('key1', 'value1'), ('key2', 'value3'), [('key1', 'value1'), ('key2', 'value3'),
('key4', 'value6')]) ('key4', 'value6')])
self.assertEqual([(k,mm.getlist(k)) for k in sorted(mm)], self.assertEqual([(k, mm.getlist(k)) for k in sorted(mm)],
[('key1', ['value1']), [('key1', ['value1']),
('key2', ['value2', 'value3']), ('key2', ['value2', 'value3']),
('key4', ['value5', 'value6'])]) ('key4', ['value5', 'value6'])])

View File

@ -24,7 +24,7 @@ class TestUtilsHtml(TestCase):
def test_escape(self): def test_escape(self):
f = html.escape f = html.escape
items = ( items = (
('&','&amp;'), ('&', '&amp;'),
('<', '&lt;'), ('<', '&lt;'),
('>', '&gt;'), ('>', '&gt;'),
('"', '&quot;'), ('"', '&quot;'),

View File

@ -17,33 +17,33 @@ class TermColorTests(unittest.TestCase):
def test_fg(self): def test_fg(self):
self.assertEqual(parse_color_setting('error=green'), self.assertEqual(parse_color_setting('error=green'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
def test_fg_bg(self): def test_fg_bg(self):
self.assertEqual(parse_color_setting('error=green/blue'), self.assertEqual(parse_color_setting('error=green/blue'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg':'blue'})) ERROR={'fg': 'green', 'bg': 'blue'}))
def test_fg_opts(self): def test_fg_opts(self):
self.assertEqual(parse_color_setting('error=green,blink'), self.assertEqual(parse_color_setting('error=green,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink',)})) ERROR={'fg': 'green', 'opts': ('blink',)}))
self.assertEqual(parse_color_setting('error=green,bold,blink'), self.assertEqual(parse_color_setting('error=green,bold,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink','bold')})) ERROR={'fg': 'green', 'opts': ('blink', 'bold')}))
def test_fg_bg_opts(self): def test_fg_bg_opts(self):
self.assertEqual(parse_color_setting('error=green/blue,blink'), self.assertEqual(parse_color_setting('error=green/blue,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg':'blue', 'opts': ('blink',)})) ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)}))
self.assertEqual(parse_color_setting('error=green/blue,bold,blink'), self.assertEqual(parse_color_setting('error=green/blue,bold,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg':'blue', 'opts': ('blink','bold')})) ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink', 'bold')}))
def test_override_palette(self): def test_override_palette(self):
self.assertEqual(parse_color_setting('light;error=green'), self.assertEqual(parse_color_setting('light;error=green'),
dict(PALETTES[LIGHT_PALETTE], dict(PALETTES[LIGHT_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
def test_override_nocolor(self): def test_override_nocolor(self):
self.assertEqual(parse_color_setting('nocolor;error=green'), self.assertEqual(parse_color_setting('nocolor;error=green'),
@ -56,14 +56,14 @@ class TermColorTests(unittest.TestCase):
def test_multiple_roles(self): def test_multiple_roles(self):
self.assertEqual(parse_color_setting('error=green;sql_field=blue'), self.assertEqual(parse_color_setting('error=green;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'}, ERROR={'fg': 'green'},
SQL_FIELD={'fg':'blue'})) SQL_FIELD={'fg': 'blue'}))
def test_override_with_multiple_roles(self): def test_override_with_multiple_roles(self):
self.assertEqual(parse_color_setting('light;error=green;sql_field=blue'), self.assertEqual(parse_color_setting('light;error=green;sql_field=blue'),
dict(PALETTES[LIGHT_PALETTE], dict(PALETTES[LIGHT_PALETTE],
ERROR={'fg':'green'}, ERROR={'fg': 'green'},
SQL_FIELD={'fg':'blue'})) SQL_FIELD={'fg': 'blue'}))
def test_empty_definition(self): def test_empty_definition(self):
self.assertEqual(parse_color_setting(';'), None) self.assertEqual(parse_color_setting(';'), None)
@ -73,13 +73,13 @@ class TermColorTests(unittest.TestCase):
def test_empty_options(self): def test_empty_options(self):
self.assertEqual(parse_color_setting('error=green,'), self.assertEqual(parse_color_setting('error=green,'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=green,,,'), self.assertEqual(parse_color_setting('error=green,,,'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=green,,blink,,'), self.assertEqual(parse_color_setting('error=green,,blink,,'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink',)})) ERROR={'fg': 'green', 'opts': ('blink',)}))
def test_bad_palette(self): def test_bad_palette(self):
self.assertEqual(parse_color_setting('unknown'), None) self.assertEqual(parse_color_setting('unknown'), None)
@ -89,66 +89,66 @@ class TermColorTests(unittest.TestCase):
self.assertEqual(parse_color_setting('unknown=green'), None) self.assertEqual(parse_color_setting('unknown=green'), None)
self.assertEqual(parse_color_setting('unknown=green;sql_field=blue'), self.assertEqual(parse_color_setting('unknown=green;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
SQL_FIELD={'fg':'blue'})) SQL_FIELD={'fg': 'blue'}))
def test_bad_color(self): def test_bad_color(self):
self.assertEqual(parse_color_setting('error='), None) self.assertEqual(parse_color_setting('error='), None)
self.assertEqual(parse_color_setting('error=;sql_field=blue'), self.assertEqual(parse_color_setting('error=;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
SQL_FIELD={'fg':'blue'})) SQL_FIELD={'fg': 'blue'}))
self.assertEqual(parse_color_setting('error=unknown'), None) self.assertEqual(parse_color_setting('error=unknown'), None)
self.assertEqual(parse_color_setting('error=unknown;sql_field=blue'), self.assertEqual(parse_color_setting('error=unknown;sql_field=blue'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
SQL_FIELD={'fg':'blue'})) SQL_FIELD={'fg': 'blue'}))
self.assertEqual(parse_color_setting('error=green/unknown'), self.assertEqual(parse_color_setting('error=green/unknown'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=green/blue/something'), self.assertEqual(parse_color_setting('error=green/blue/something'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg': 'blue'})) ERROR={'fg': 'green', 'bg': 'blue'}))
self.assertEqual(parse_color_setting('error=green/blue/something,blink'), self.assertEqual(parse_color_setting('error=green/blue/something,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg': 'blue', 'opts': ('blink',)})) ERROR={'fg': 'green', 'bg': 'blue', 'opts': ('blink',)}))
def test_bad_option(self): def test_bad_option(self):
self.assertEqual(parse_color_setting('error=green,unknown'), self.assertEqual(parse_color_setting('error=green,unknown'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=green,unknown,blink'), self.assertEqual(parse_color_setting('error=green,unknown,blink'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink',)})) ERROR={'fg': 'green', 'opts': ('blink',)}))
def test_role_case(self): def test_role_case(self):
self.assertEqual(parse_color_setting('ERROR=green'), self.assertEqual(parse_color_setting('ERROR=green'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('eRrOr=green'), self.assertEqual(parse_color_setting('eRrOr=green'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
def test_color_case(self): def test_color_case(self):
self.assertEqual(parse_color_setting('error=GREEN'), self.assertEqual(parse_color_setting('error=GREEN'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=GREEN/BLUE'), self.assertEqual(parse_color_setting('error=GREEN/BLUE'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg':'blue'})) ERROR={'fg': 'green', 'bg': 'blue'}))
self.assertEqual(parse_color_setting('error=gReEn'), self.assertEqual(parse_color_setting('error=gReEn'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green'})) ERROR={'fg': 'green'}))
self.assertEqual(parse_color_setting('error=gReEn/bLuE'), self.assertEqual(parse_color_setting('error=gReEn/bLuE'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'bg':'blue'})) ERROR={'fg': 'green', 'bg': 'blue'}))
def test_opts_case(self): def test_opts_case(self):
self.assertEqual(parse_color_setting('error=green,BLINK'), self.assertEqual(parse_color_setting('error=green,BLINK'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink',)})) ERROR={'fg': 'green', 'opts': ('blink',)}))
self.assertEqual(parse_color_setting('error=green,bLiNk'), self.assertEqual(parse_color_setting('error=green,bLiNk'),
dict(PALETTES[NOCOLOR_PALETTE], dict(PALETTES[NOCOLOR_PALETTE],
ERROR={'fg':'green', 'opts': ('blink',)})) ERROR={'fg': 'green', 'opts': ('blink',)}))
def test_colorize_empty_text(self): def test_colorize_empty_text(self):
self.assertEqual(colorize(text=None), '\x1b[m\x1b[0m') self.assertEqual(colorize(text=None), '\x1b[m\x1b[0m')

View File

@ -90,7 +90,7 @@ class PerformUniqueChecksTest(TestCase):
p.full_clean() p.full_clean()
# Should work without errors # Should work without errors
p = Post(title="Django 1.0 is released", posted=datetime.datetime(2008, 9,4)) p = Post(title="Django 1.0 is released", posted=datetime.datetime(2008, 9, 4))
p.full_clean() p.full_clean()
p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1)) p = Post(slug="Django 1.0", posted=datetime.datetime(2008, 1, 1))

View File

@ -119,9 +119,9 @@ class GenericIPAddressFieldTests(ValidationTestCase):
def test_invalid_generic_ip_raises_error(self): def test_invalid_generic_ip_raises_error(self):
giptm = GenericIPAddressTestModel(generic_ip="294.4.2.1") giptm = GenericIPAddressTestModel(generic_ip="294.4.2.1")
self.assertFailsValidation(giptm.full_clean, ['generic_ip',]) self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
giptm = GenericIPAddressTestModel(generic_ip="1:2") giptm = GenericIPAddressTestModel(generic_ip="1:2")
self.assertFailsValidation(giptm.full_clean, ['generic_ip',]) self.assertFailsValidation(giptm.full_clean, ['generic_ip'])
def test_correct_v4_ip_passes(self): def test_correct_v4_ip_passes(self):
giptm = GenericIPAddressTestModel(v4_ip="1.2.3.4") giptm = GenericIPAddressTestModel(v4_ip="1.2.3.4")
@ -161,7 +161,7 @@ class GenericIPAddressFieldTests(ValidationTestCase):
giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="::ffff:18.52.18.52") giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="::ffff:18.52.18.52")
giptm.save() giptm.save()
giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="18.52.18.52") giptm = GenericIPAddrUnpackUniqueTest(generic_v4unpack_ip="18.52.18.52")
self.assertFailsValidation(giptm.full_clean, ['generic_v4unpack_ip',]) self.assertFailsValidation(giptm.full_clean, ['generic_v4unpack_ip'])
def test_empty_generic_ip_passes(self): def test_empty_generic_ip_passes(self):
giptm = GenericIPAddressTestModel(generic_ip="") giptm = GenericIPAddressTestModel(generic_ip="")

View File

@ -304,7 +304,7 @@ class ExceptionReportTestMixin(object):
breakfast_data = {'sausage-key': 'sausage-value', breakfast_data = {'sausage-key': 'sausage-value',
'baked-beans-key': 'baked-beans-value', 'baked-beans-key': 'baked-beans-value',
'hash-brown-key': 'hash-brown-value', 'hash-brown-key': 'hash-brown-value',
'bacon-key': 'bacon-value',} 'bacon-key': 'bacon-value'}
def verify_unsafe_response(self, view, check_for_vars=True, def verify_unsafe_response(self, view, check_for_vars=True,
check_for_POST_params=True): check_for_POST_params=True):