1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Removed unused local variables in tests.

This commit is contained in:
Tim Graham 2013-10-19 08:31:38 -04:00
parent 5f52590368
commit 96d1d4e292
72 changed files with 309 additions and 339 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 exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py
ignore=E124,E125,E126,E127,E128,E225,E226,E241,E251,E302,E501,E203,E221,E227,E231,E261,E301,F401,F403,F841,W601 ignore=E124,E125,E126,E127,E128,E225,E226,E241,E251,E302,E501,E203,E221,E227,E231,E261,E301,F401,F403,W601
[metadata] [metadata]
license-file = LICENSE license-file = LICENSE

View File

@ -168,7 +168,7 @@ class DeprecatingRequestMergeDictTest(SimpleTestCase):
with warnings.catch_warnings(record=True) as recorded: with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter('always') warnings.simplefilter('always')
request = RequestFactory().get('/') request = RequestFactory().get('/')
_ = request.REQUEST request.REQUEST # evaluate
msgs = [str(warning.message) for warning in recorded] msgs = [str(warning.message) for warning in recorded]
self.assertEqual(msgs, [ self.assertEqual(msgs, [

View File

@ -351,7 +351,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_mult(self): def test_delta_invalid_op_mult(self):
raised = False raised = False
try: try:
r = repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0])) repr(Experiment.objects.filter(end__lt=F('start')*self.deltas[0]))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to multiply datetime by timedelta.")
@ -359,7 +359,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_div(self): def test_delta_invalid_op_div(self):
raised = False raised = False
try: try:
r = repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0])) repr(Experiment.objects.filter(end__lt=F('start')/self.deltas[0]))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to divide datetime by timedelta.")
@ -367,7 +367,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_mod(self): def test_delta_invalid_op_mod(self):
raised = False raised = False
try: try:
r = repr(Experiment.objects.filter(end__lt=F('start') % self.deltas[0])) repr(Experiment.objects.filter(end__lt=F('start') % self.deltas[0]))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to modulo divide datetime by timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to modulo divide datetime by timedelta.")
@ -375,7 +375,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_and(self): def test_delta_invalid_op_and(self):
raised = False raised = False
try: try:
r = repr(Experiment.objects.filter(end__lt=F('start').bitand(self.deltas[0]))) repr(Experiment.objects.filter(end__lt=F('start').bitand(self.deltas[0])))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to binary and a datetime with a timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to binary and a datetime with a timedelta.")
@ -383,7 +383,7 @@ class FTimeDeltaTests(TestCase):
def test_delta_invalid_op_or(self): def test_delta_invalid_op_or(self):
raised = False raised = False
try: try:
r = repr(Experiment.objects.filter(end__lt=F('start').bitor(self.deltas[0]))) repr(Experiment.objects.filter(end__lt=F('start').bitor(self.deltas[0])))
except TypeError: except TypeError:
raised = True raised = True
self.assertTrue(raised, "TypeError not raised on attempt to binary or a datetime with a timedelta.") self.assertTrue(raised, "TypeError not raised on attempt to binary or a datetime with a timedelta.")

View File

@ -160,7 +160,7 @@ class ExtraRegressTests(TestCase):
columns, we can (and should) ignore those columns. They don't change columns, we can (and should) ignore those columns. They don't change
the result and cause incorrect SQL to be produced otherwise. the result and cause incorrect SQL to be produced otherwise.
""" """
rm = RevisionableModel.objects.create( RevisionableModel.objects.create(
title='First Revision', title='First Revision',
when=datetime.datetime(2008, 9, 28, 10, 30, 0) when=datetime.datetime(2008, 9, 28, 10, 30, 0)
) )

View File

@ -174,7 +174,7 @@ class FieldDeconstructionTests(TestCase):
self.assertEqual(kwargs, {}) self.assertEqual(kwargs, {})
def test_ip_address_field(self): def test_ip_address_field(self):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
field = models.IPAddressField() field = models.IPAddressField()
name, path, args, kwargs = field.deconstruct() name, path, args, kwargs = field.deconstruct()

View File

@ -241,8 +241,8 @@ class FileStorageTests(unittest.TestCase):
self.assertFalse(self.storage.exists('storage_test_2')) self.assertFalse(self.storage.exists('storage_test_2'))
self.assertFalse(self.storage.exists('storage_dir_1')) self.assertFalse(self.storage.exists('storage_dir_1'))
f = self.storage.save('storage_test_1', ContentFile('custom content')) self.storage.save('storage_test_1', ContentFile('custom content'))
f = self.storage.save('storage_test_2', ContentFile('custom content')) self.storage.save('storage_test_2', ContentFile('custom content'))
os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1')) os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
dirs, files = self.storage.listdir('') dirs, files = self.storage.listdir('')
@ -428,7 +428,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
def test_race_condition(self): def test_race_condition(self):
self.thread.start() self.thread.start()
name = self.save_file('conflict') self.save_file('conflict')
self.thread.join() self.thread.join()
self.assertTrue(self.storage.exists('conflict')) self.assertTrue(self.storage.exists('conflict'))
self.assertTrue(self.storage.exists('conflict_1')) self.assertTrue(self.storage.exists('conflict_1'))

View File

@ -335,7 +335,7 @@ class FileUploadTests(TestCase):
"""A handler that'll access POST during an exception.""" """A handler that'll access POST during an exception."""
def handle_uncaught_exception(self, request, resolver, exc_info): def handle_uncaught_exception(self, request, resolver, exc_info):
ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info) ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
p = request.POST request.POST # evaluate
return ret return ret
# Maybe this is a little more complicated that it needs to be; but if # Maybe this is a little more complicated that it needs to be; but if
@ -356,7 +356,7 @@ class FileUploadTests(TestCase):
'file_field': fp, 'file_field': fp,
} }
try: try:
response = self.client.post('/file_uploads/upload_errors/', post_data) self.client.post('/file_uploads/upload_errors/', post_data)
except reference_error.__class__ as err: except reference_error.__class__ as err:
self.assertFalse( self.assertFalse(
str(err) == str(reference_error), str(err) == str(reference_error),
@ -444,7 +444,7 @@ class MultiParserTests(unittest.TestCase):
def test_empty_upload_handlers(self): def test_empty_upload_handlers(self):
# We're not actually parsing here; just checking if the parser properly # We're not actually parsing here; just checking if the parser properly
# instantiates with empty upload handlers. # instantiates with empty upload handlers.
parser = MultiPartParser({ MultiPartParser({
'CONTENT_TYPE': 'multipart/form-data; boundary=_foo', 'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
'CONTENT_LENGTH': '1' 'CONTENT_LENGTH': '1'
}, StringIO('x'), [], 'utf-8') }, StringIO('x'), [], 'utf-8')

View File

@ -170,7 +170,7 @@ class FileTests(unittest.TestCase):
# See #14681, stdlib gzip module crashes if mode is set to None # See #14681, stdlib gzip module crashes if mode is set to None
file = SimpleUploadedFile("mode_test.txt", b"content") file = SimpleUploadedFile("mode_test.txt", b"content")
self.assertFalse(hasattr(file, 'mode')) self.assertFalse(hasattr(file, 'mode'))
g = gzip.GzipFile(fileobj=file) gzip.GzipFile(fileobj=file)
class FileMoveSafeTests(unittest.TestCase): class FileMoveSafeTests(unittest.TestCase):

View File

@ -194,7 +194,7 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
'required': 'REQUIRED', 'required': 'REQUIRED',
'invalid': 'INVALID IP ADDRESS', 'invalid': 'INVALID IP ADDRESS',
} }
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
f = IPAddressField(error_messages=e) f = IPAddressField(error_messages=e)
self.assertFormErrors(['REQUIRED'], f.clean, '') self.assertFormErrors(['REQUIRED'], f.clean, '')
@ -243,9 +243,9 @@ class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
def test_modelchoicefield(self): def test_modelchoicefield(self):
# Create choices for the model choice field tests below. # Create choices for the model choice field tests below.
from forms_tests.models import ChoiceModel from forms_tests.models import ChoiceModel
c1 = ChoiceModel.objects.create(pk=1, name='a') ChoiceModel.objects.create(pk=1, name='a')
c2 = ChoiceModel.objects.create(pk=2, name='b') ChoiceModel.objects.create(pk=2, name='b')
c3 = ChoiceModel.objects.create(pk=3, name='c') ChoiceModel.objects.create(pk=3, name='c')
# ModelChoiceField # ModelChoiceField
e = { e = {

View File

@ -535,7 +535,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00') self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')
def test_ipaddress(self): def test_ipaddress(self):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
f = IPAddressField() f = IPAddressField()
self.assertFormErrors(['This field is required.'], f.clean, '') self.assertFormErrors(['This field is required.'], f.clean, '')
@ -546,7 +546,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5') self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '1.2.3.4.5')
self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5') self.assertFormErrors(['Enter a valid IPv4 address.'], f.clean, '256.125.1.5')
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
f = IPAddressField(required=False) f = IPAddressField(required=False)
self.assertEqual(f.clean(''), '') self.assertEqual(f.clean(''), '')

View File

@ -336,20 +336,6 @@ class FormsFormsetTestCase(TestCase):
def test_more_initial_data(self): def test_more_initial_data(self):
# The extra argument also works when the formset is pre-filled with initial # The extra argument also works when the formset is pre-filled with initial
# data. # data.
data = {
'choices-TOTAL_FORMS': '3', # the number of forms rendered
'choices-INITIAL_FORMS': '0', # the number of forms with initial data
'choices-MIN_NUM_FORMS': '0', # min number of forms
'choices-MAX_NUM_FORMS': '0', # max number of forms
'choices-0-choice': 'Calexico',
'choices-0-votes': '100',
'choices-1-choice': '',
'choices-1-votes': '', # missing value
'choices-2-choice': '',
'choices-2-votes': '',
}
initial = [{'choice': 'Calexico', 'votes': 100}] initial = [{'choice': 'Calexico', 'votes': 100}]
ChoiceFormSet = formset_factory(Choice, extra=3) ChoiceFormSet = formset_factory(Choice, extra=3)
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices') formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')

View File

@ -94,9 +94,9 @@ class ModelFormCallableModelDefault(TestCase):
def test_callable_initial_value(self): def test_callable_initial_value(self):
"The initial value for a callable default returning a queryset is the pk (refs #13769)" "The initial value for a callable default returning a queryset is the pk (refs #13769)"
obj1 = ChoiceOptionModel.objects.create(id=1, name='default') ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertHTMLEqual(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice"> self.assertHTMLEqual(ChoiceFieldForm().as_p(), """<p><label for="id_choice">Choice:</label> <select name="choice" id="id_choice">
<option value="1" selected="selected">ChoiceOption 1</option> <option value="1" selected="selected">ChoiceOption 1</option>
<option value="2">ChoiceOption 2</option> <option value="2">ChoiceOption 2</option>
@ -120,7 +120,7 @@ class ModelFormCallableModelDefault(TestCase):
def test_initial_instance_value(self): def test_initial_instance_value(self):
"Initial instances for model fields may also be instances (refs #7287)" "Initial instances for model fields may also be instances (refs #7287)"
obj1 = ChoiceOptionModel.objects.create(id=1, name='default') ChoiceOptionModel.objects.create(id=1, name='default')
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2') obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3') obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
self.assertHTMLEqual(ChoiceFieldForm(initial={ self.assertHTMLEqual(ChoiceFieldForm(initial={

View File

@ -178,7 +178,6 @@ class GenericInlineAdminParametersTest(TestCase):
With extra=5 and max_num=2, there should be only 2 forms. With extra=5 and max_num=2, there should be only 2 forms.
""" """
e = self._create_object(EpisodeMaxNum) e = self._create_object(EpisodeMaxNum)
inline_form_data = '<input type="hidden" name="generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" value="2" id="id_generic_inline_admin-media-content_type-object_id-TOTAL_FORMS" /><input type="hidden" name="generic_inline_admin-media-content_type-object_id-INITIAL_FORMS" value="1" id="id_generic_inline_admin-media-content_type-object_id-INITIAL_FORMS" />'
response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodemaxnum/%s/' % e.pk) response = self.client.get('/generic_inline_admin/admin/generic_inline_admin/episodemaxnum/%s/' % e.pk)
formset = response.context['inline_admin_formsets'][0].formset formset = response.context['inline_admin_formsets'][0].formset
self.assertEqual(formset.total_form_count(), 2) self.assertEqual(formset.total_form_count(), 2)
@ -422,13 +421,13 @@ class GenericInlineModelAdminTest(TestCase):
def get_formsets(self, request, obj=None): def get_formsets(self, request, obj=None):
# Catch the deprecation warning to force the usage of get_formsets # Catch the deprecation warning to force the usage of get_formsets
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
return super(EpisodeAdmin, self).get_formsets(request, obj) return super(EpisodeAdmin, self).get_formsets(request, obj)
ma = EpisodeAdmin(Episode, self.site) ma = EpisodeAdmin(Episode, self.site)
inlines = ma.get_inline_instances(request) inlines = ma.get_inline_instances(request)
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
for (formset, inline), other_inline in zip(ma.get_formsets_with_inlines(request), inlines): for (formset, inline), other_inline in zip(ma.get_formsets_with_inlines(request), inlines):
self.assertIsInstance(formset, other_inline.get_formset(request).__class__) self.assertIsInstance(formset, other_inline.get_formset(request).__class__)

View File

@ -19,7 +19,7 @@ class GenericRelationsTests(TestCase):
platypus = Animal.objects.create( platypus = Animal.objects.create(
common_name="Platypus", latin_name="Ornithorhynchus anatinus" common_name="Platypus", latin_name="Ornithorhynchus anatinus"
) )
eggplant = Vegetable.objects.create(name="Eggplant", is_yucky=True) Vegetable.objects.create(name="Eggplant", is_yucky=True)
bacon = Vegetable.objects.create(name="Bacon", is_yucky=False) bacon = Vegetable.objects.create(name="Bacon", is_yucky=False)
quartz = Mineral.objects.create(name="Quartz", hardness=7) quartz = Mineral.objects.create(name="Quartz", hardness=7)
@ -46,7 +46,7 @@ class GenericRelationsTests(TestCase):
# Recall that the Mineral class doesn't have an explicit GenericRelation # Recall that the Mineral class doesn't have an explicit GenericRelation
# defined. That's OK, because you can create TaggedItems explicitly. # defined. That's OK, because you can create TaggedItems explicitly.
tag1 = TaggedItem.objects.create(content_object=quartz, tag="shiny") tag1 = TaggedItem.objects.create(content_object=quartz, tag="shiny")
tag2 = TaggedItem.objects.create(content_object=quartz, tag="clearish") TaggedItem.objects.create(content_object=quartz, tag="clearish")
# However, excluding GenericRelations means your lookups have to be a # However, excluding GenericRelations means your lookups have to be a
# bit more explicit. # bit more explicit.

View File

@ -76,7 +76,7 @@ class ViewTest(unittest.TestCase):
Test that a view can't be accidentally instantiated before deployment Test that a view can't be accidentally instantiated before deployment
""" """
try: try:
view = SimpleView(key='value').as_view() SimpleView(key='value').as_view()
self.fail('Should not be able to instantiate a view') self.fail('Should not be able to instantiate a view')
except AttributeError: except AttributeError:
pass pass
@ -86,7 +86,7 @@ class ViewTest(unittest.TestCase):
Test that a view can't be accidentally instantiated before deployment Test that a view can't be accidentally instantiated before deployment
""" """
try: try:
view = SimpleView.as_view('value') SimpleView.as_view('value')
self.fail('Should not be able to use non-keyword arguments instantiating a view') self.fail('Should not be able to use non-keyword arguments instantiating a view')
except TypeError: except TypeError:
pass pass

View File

@ -12,7 +12,7 @@ from .models import Book, BookSigning
def _make_books(n, base_date): def _make_books(n, base_date):
for i in range(n): for i in range(n):
b = Book.objects.create( Book.objects.create(
name='Book %d' % i, name='Book %d' % i,
slug='book-%d' % i, slug='book-%d' % i,
pages=100+i, pages=100+i,
@ -158,7 +158,7 @@ class YearArchiveViewTests(TestCase):
def test_year_view_allow_future(self): def test_year_view_allow_future(self):
# Create a new book in the future # Create a new book in the future
year = datetime.date.today().year + 1 year = datetime.date.today().year + 1
b = Book.objects.create(name="The New New Testement", pages=600, pubdate=datetime.date(year, 1, 1)) Book.objects.create(name="The New New Testement", pages=600, pubdate=datetime.date(year, 1, 1))
res = self.client.get('/dates/books/%s/' % year) res = self.client.get('/dates/books/%s/' % year)
self.assertEqual(res.status_code, 404) self.assertEqual(res.status_code, 404)

View File

@ -122,15 +122,15 @@ class CreateViewTests(TestCase):
def test_create_without_redirect(self): def test_create_without_redirect(self):
try: try:
res = self.client.post('/edit/authors/create/naive/', self.client.post('/edit/authors/create/naive/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
except ImproperlyConfigured: except ImproperlyConfigured:
pass pass
def test_create_restricted(self): def test_create_restricted(self):
res = self.client.post('/edit/authors/create/restricted/', res = self.client.post('/edit/authors/create/restricted/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'}) {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302) self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/accounts/login/?next=/edit/authors/create/restricted/') self.assertRedirects(res, 'http://testserver/accounts/login/?next=/edit/authors/create/restricted/')
@ -278,16 +278,15 @@ class UpdateViewTests(TestCase):
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>']) self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
def test_update_without_redirect(self): def test_update_without_redirect(self):
try: a = Author.objects.create(
a = Author.objects.create( name='Randall Munroe',
name='Randall Munroe', slug='randall-munroe',
slug='randall-munroe', )
) # Should raise exception -- No redirect URL provided, and no
res = self.client.post('/edit/author/%d/update/naive/' % a.pk, # get_absolute_url provided
with self.assertRaises(ImproperlyConfigured):
self.client.post('/edit/author/%d/update/naive/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}) {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
except ImproperlyConfigured:
pass
def test_update_get_object(self): def test_update_get_object(self):
a = Author.objects.create( a = Author.objects.create(
@ -365,12 +364,11 @@ class DeleteViewTests(TestCase):
self.assertQuerysetEqual(Author.objects.all(), []) self.assertQuerysetEqual(Author.objects.all(), [])
def test_delete_without_redirect(self): def test_delete_without_redirect(self):
try: a = Author.objects.create(
a = Author.objects.create( name='Randall Munroe',
name='Randall Munroe', slug='randall-munroe',
slug='randall-munroe', )
) # Should raise exception -- No redirect URL provided, and no
res = self.client.post('/edit/author/%d/delete/naive/' % a.pk) # get_absolute_url provided
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided') with self.assertRaises(ImproperlyConfigured):
except ImproperlyConfigured: self.client.post('/edit/author/%d/delete/naive/' % a.pk)
pass

View File

@ -27,11 +27,11 @@ class EarliestOrLatestTests(TestCase):
headline="Article 2", pub_date=datetime(2005, 7, 27), headline="Article 2", pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 7, 28) expire_date=datetime(2005, 7, 28)
) )
a3 = Article.objects.create( Article.objects.create(
headline="Article 3", pub_date=datetime(2005, 7, 28), headline="Article 3", pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 8, 27) expire_date=datetime(2005, 8, 27)
) )
a4 = Article.objects.create( Article.objects.create(
headline="Article 4", pub_date=datetime(2005, 7, 28), headline="Article 4", pub_date=datetime(2005, 7, 28),
expire_date=datetime(2005, 7, 30) expire_date=datetime(2005, 7, 30)
) )
@ -72,7 +72,7 @@ class EarliestOrLatestTests(TestCase):
headline="Article 1", pub_date=datetime(2005, 7, 26), headline="Article 1", pub_date=datetime(2005, 7, 26),
expire_date=datetime(2005, 9, 1) expire_date=datetime(2005, 9, 1)
) )
a2 = Article.objects.create( Article.objects.create(
headline="Article 2", pub_date=datetime(2005, 7, 27), headline="Article 2", pub_date=datetime(2005, 7, 27),
expire_date=datetime(2005, 7, 28) expire_date=datetime(2005, 7, 28)
) )
@ -117,7 +117,7 @@ class EarliestOrLatestTests(TestCase):
def test_latest_manual(self): def test_latest_manual(self):
# You can still use latest() with a model that doesn't have # You can still use latest() with a model that doesn't have
# "get_latest_by" set -- just pass in the field name manually. # "get_latest_by" set -- just pass in the field name manually.
p1 = Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1)) Person.objects.create(name="Ralph", birthday=datetime(1950, 1, 1))
p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3)) p2 = Person.objects.create(name="Stephanie", birthday=datetime(1960, 2, 3))
self.assertRaises(AssertionError, Person.objects.latest) self.assertRaises(AssertionError, Person.objects.latest)
self.assertEqual(Person.objects.latest("birthday"), p2) self.assertEqual(Person.objects.latest("birthday"), p2)

View File

@ -51,7 +51,7 @@ class GetOrCreateTests(TestCase):
# If you specify an existing primary key, but different other fields, # If you specify an existing primary key, but different other fields,
# then you will get an error and data will not be updated. # then you will get an error and data will not be updated.
m = ManualPrimaryKeyTest.objects.create(id=1, data="Original") ManualPrimaryKeyTest.objects.create(id=1, data="Original")
self.assertRaises(IntegrityError, self.assertRaises(IntegrityError,
ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different" ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
) )
@ -63,7 +63,7 @@ class GetOrCreateTests(TestCase):
# the actual traceback. Refs #16340. # the actual traceback. Refs #16340.
try: try:
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different") ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
except IntegrityError as e: except IntegrityError:
formatted_traceback = traceback.format_exc() formatted_traceback = traceback.format_exc()
self.assertIn(str('obj.save'), formatted_traceback) self.assertIn(str('obj.save'), formatted_traceback)
@ -193,6 +193,6 @@ class UpdateOrCreateTests(TestCase):
# the actual traceback. Refs #16340. # the actual traceback. Refs #16340.
try: try:
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different") ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different")
except IntegrityError as e: except IntegrityError:
formatted_traceback = traceback.format_exc() formatted_traceback = traceback.format_exc()
self.assertIn('obj.save', formatted_traceback) self.assertIn('obj.save', formatted_traceback)

View File

@ -1198,16 +1198,16 @@ class LocaleMiddlewareTests(TransRealMixin, TestCase):
# Clear the session data before request # Clear the session data before request
session.save() session.save()
response = self.client.get('/en/simple/') self.client.get('/en/simple/')
self.assertEqual(self.client.session['django_language'], 'en') self.assertEqual(self.client.session['django_language'], 'en')
# Clear the session data before request # Clear the session data before request
session.save() session.save()
response = self.client.get('/fr/simple/') self.client.get('/fr/simple/')
self.assertEqual(self.client.session['django_language'], 'fr') self.assertEqual(self.client.session['django_language'], 'fr')
# Check that language is not changed in session # Check that language is not changed in session
response = self.client.get('/en/simple/') self.client.get('/en/simple/')
self.assertEqual(self.client.session['django_language'], 'fr') self.assertEqual(self.client.session['django_language'], 'fr')

View File

@ -362,12 +362,12 @@ class SecurityLoggerTest(TestCase):
def test_suspicious_operation_creates_log_message(self): def test_suspicious_operation_creates_log_message(self):
with patch_logger('django.security.SuspiciousOperation', 'error') as calls: with patch_logger('django.security.SuspiciousOperation', 'error') as calls:
response = self.client.get('/suspicious/') self.client.get('/suspicious/')
self.assertEqual(len(calls), 1) self.assertEqual(len(calls), 1)
self.assertEqual(calls[0], 'dubious') self.assertEqual(calls[0], 'dubious')
def test_suspicious_operation_uses_sublogger(self): def test_suspicious_operation_uses_sublogger(self):
with patch_logger('django.security.DisallowedHost', 'error') as calls: with patch_logger('django.security.DisallowedHost', 'error') as calls:
response = self.client.get('/suspicious_spec/') self.client.get('/suspicious_spec/')
self.assertEqual(len(calls), 1) self.assertEqual(len(calls), 1)
self.assertEqual(calls[0], 'dubious') self.assertEqual(calls[0], 'dubious')

View File

@ -394,9 +394,9 @@ class LookupTests(TestCase):
['<Article: Article with \ backslash>']) ['<Article: Article with \ backslash>'])
def test_exclude(self): def test_exclude(self):
a8 = Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20))
a9 = Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21))
a10 = Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))
# exclude() is the opposite of filter() when doing lookups: # exclude() is the opposite of filter() when doing lookups:
self.assertQuerysetEqual( self.assertQuerysetEqual(

View File

@ -24,9 +24,9 @@ class M2mThroughTests(TestCase):
[] []
) )
# To make Jim a member of Group Rock, simply create a Membership object. # To make Jim a member of Group Rock, simply create a Membership object.
m1 = Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.rock)
# We can do the same for Jane and Rock. # We can do the same for Jane and Rock.
m2 = Membership.objects.create(person=self.jane, group=self.rock) Membership.objects.create(person=self.jane, group=self.rock)
# Let's check to make sure that it worked. Jane and Jim should be members of Rock. # Let's check to make sure that it worked. Jane and Jim should be members of Rock.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.rock.members.all(), [ self.rock.members.all(), [
@ -36,9 +36,9 @@ class M2mThroughTests(TestCase):
attrgetter("name") attrgetter("name")
) )
# Now we can add a bunch more Membership objects to test with. # Now we can add a bunch more Membership objects to test with.
m3 = Membership.objects.create(person=self.bob, group=self.roll) Membership.objects.create(person=self.bob, group=self.roll)
m4 = Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll)
m5 = Membership.objects.create(person=self.jane, group=self.roll) Membership.objects.create(person=self.jane, group=self.roll)
# We can get Jim's Group membership as with any ForeignKey. # We can get Jim's Group membership as with any ForeignKey.
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.jim.group_set.all(), [ self.jim.group_set.all(), [
@ -161,8 +161,8 @@ class M2mThroughTests(TestCase):
[] []
) )
cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.bob, group=self.rock)
cm2 = CustomMembership.objects.create(person=self.jim, group=self.rock) CustomMembership.objects.create(person=self.jim, group=self.rock)
# 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(
@ -195,7 +195,7 @@ class M2mThroughTests(TestCase):
) )
chris = PersonSelfRefM2M.objects.create(name="Chris") chris = PersonSelfRefM2M.objects.create(name="Chris")
f = Friendship.objects.create(first=tony, second=chris, date_friended=datetime.now()) Friendship.objects.create(first=tony, second=chris, date_friended=datetime.now())
# Tony should now show that Chris is his friend. # Tony should now show that Chris is his friend.
self.assertQuerysetEqual( self.assertQuerysetEqual(
@ -209,7 +209,7 @@ class M2mThroughTests(TestCase):
chris.friends.all(), chris.friends.all(),
[] []
) )
f2 = Friendship.objects.create(first=chris, second=tony, date_friended=datetime.now()) Friendship.objects.create(first=chris, second=tony, date_friended=datetime.now())
# 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.
@ -236,10 +236,10 @@ class M2mThroughTests(TestCase):
) )
def test_query_tests(self): def test_query_tests(self):
m1 = Membership.objects.create(person=self.jim, group=self.rock) Membership.objects.create(person=self.jim, group=self.rock)
m2 = Membership.objects.create(person=self.jane, group=self.rock) m2 = Membership.objects.create(person=self.jane, group=self.rock)
m3 = Membership.objects.create(person=self.bob, group=self.roll) m3 = Membership.objects.create(person=self.bob, group=self.roll)
m4 = Membership.objects.create(person=self.jim, group=self.roll) Membership.objects.create(person=self.jim, group=self.roll)
m5 = Membership.objects.create(person=self.jane, group=self.roll) m5 = Membership.objects.create(person=self.jane, group=self.roll)
m2.invite_reason = "She was just awesome." m2.invite_reason = "She was just awesome."
@ -278,8 +278,8 @@ class M2mThroughTests(TestCase):
attrgetter("name") attrgetter("name")
) )
cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock) CustomMembership.objects.create(person=self.bob, group=self.rock)
cm2 = 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"),[

View File

@ -56,7 +56,7 @@ class ManyToManyTests(TestCase):
with six.assertRaisesRegex(self, TypeError, "'Publication' instance expected, got <Article.*"): with six.assertRaisesRegex(self, TypeError, "'Publication' instance expected, got <Article.*"):
a6.publications.add(a5) a6.publications.add(a5)
# Add a Publication directly via publications.add by using keyword arguments. # Add a Publication directly via publications.add by using keyword arguments.
p4 = a6.publications.create(title='Highlights for Adults') a6.publications.create(title='Highlights for Adults')
self.assertQuerysetEqual(a6.publications.all(), self.assertQuerysetEqual(a6.publications.all(),
[ [
'<Publication: Highlights for Adults>', '<Publication: Highlights for Adults>',
@ -81,7 +81,7 @@ class ManyToManyTests(TestCase):
['<Publication: Science News>']) ['<Publication: Science News>'])
# Adding via the other end using keywords # Adding via the other end using keywords
new_article = self.p2.article_set.create(headline='Carbon-free diet works wonders') self.p2.article_set.create(headline='Carbon-free diet works wonders')
self.assertQuerysetEqual( self.assertQuerysetEqual(
self.p2.article_set.all(), self.p2.article_set.all(),
[ [

View File

@ -118,10 +118,10 @@ class ManyToOneTests(TestCase):
self.assertFalse(hasattr(self.r2.article_set, 'clear')) self.assertFalse(hasattr(self.r2.article_set, 'clear'))
def test_selects(self): def test_selects(self):
new_article = self.r.article_set.create(headline="John's second story", self.r.article_set.create(headline="John's second story",
pub_date=datetime.date(2005, 7, 29)) pub_date=datetime.date(2005, 7, 29))
new_article2 = self.r2.article_set.create(headline="Paul's story", self.r2.article_set.create(headline="Paul's story",
pub_date=datetime.date(2006, 1, 17)) pub_date=datetime.date(2006, 1, 17))
# Reporter objects have access to their related Article objects. # Reporter objects have access to their related Article objects.
self.assertQuerysetEqual(self.r.article_set.all(), [ self.assertQuerysetEqual(self.r.article_set.all(), [
"<Article: John's second story>", "<Article: John's second story>",
@ -239,8 +239,8 @@ class ManyToOneTests(TestCase):
def test_reverse_selects(self): def test_reverse_selects(self):
a3 = Article.objects.create(id=None, headline="Third article", a3 = Article.objects.create(id=None, headline="Third article",
pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
a4 = Article.objects.create(id=None, headline="Fourth article", Article.objects.create(id=None, headline="Fourth article",
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id)) pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
# Reporters can be queried # Reporters can be queried
self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id), self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id),
["<Reporter: John Smith>"]) ["<Reporter: John Smith>"])
@ -336,14 +336,14 @@ class ManyToOneTests(TestCase):
]) ])
def test_delete(self): def test_delete(self):
new_article = self.r.article_set.create(headline="John's second story", self.r.article_set.create(headline="John's second story",
pub_date=datetime.date(2005, 7, 29)) pub_date=datetime.date(2005, 7, 29))
new_article2 = self.r2.article_set.create(headline="Paul's story", self.r2.article_set.create(headline="Paul's story",
pub_date=datetime.date(2006, 1, 17)) pub_date=datetime.date(2006, 1, 17))
a3 = Article.objects.create(id=None, headline="Third article", Article.objects.create(id=None, headline="Third article",
pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id) pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
a4 = Article.objects.create(id=None, headline="Fourth article", Article.objects.create(id=None, headline="Fourth article",
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id)) pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
# If you delete a reporter, his articles will be deleted. # If you delete a reporter, his articles will be deleted.
self.assertQuerysetEqual(Article.objects.all(), self.assertQuerysetEqual(Article.objects.all(),
[ [

View File

@ -87,11 +87,11 @@ class ManyToOneRegressionTests(TestCase):
r3 = Record.objects.create(category=c2) r3 = Record.objects.create(category=c2)
r4 = Record.objects.create(category=c2) r4 = Record.objects.create(category=c2)
r5 = Record.objects.create(category=c3) r5 = Record.objects.create(category=c3)
r = Relation.objects.create(left=r1, right=r2) Relation.objects.create(left=r1, right=r2)
r = Relation.objects.create(left=r3, right=r4) Relation.objects.create(left=r3, right=r4)
r = Relation.objects.create(left=r1, right=r3) Relation.objects.create(left=r1, right=r3)
r = Relation.objects.create(left=r5, right=r2) Relation.objects.create(left=r5, right=r2)
r = Relation.objects.create(left=r3, right=r2) Relation.objects.create(left=r3, right=r2)
q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second']) q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second'])
self.assertQuerysetEqual(q1, ["<Relation: First - Second>"]) self.assertQuerysetEqual(q1, ["<Relation: First - Second>"])
@ -125,7 +125,6 @@ class ManyToOneRegressionTests(TestCase):
def test_related_null_to_field(self): def test_related_null_to_field(self):
c1 = Car.objects.create() c1 = Car.objects.create()
c2 = Car.objects.create()
d1 = Driver.objects.create() d1 = Driver.objects.create()
self.assertIs(d1.car, None) self.assertIs(d1.car, None)
with self.assertNumQueries(0): with self.assertNumQueries(0):

View File

@ -117,7 +117,7 @@ class BaseMiddlewareExceptionTest(TestCase):
def assert_exceptions_handled(self, url, errors, extra_error=None): def assert_exceptions_handled(self, url, errors, extra_error=None):
try: try:
response = self.client.get(url) self.client.get(url)
except TestException: except TestException:
# Test client intentionally re-raises any exceptions being raised # Test client intentionally re-raises any exceptions being raised
# during request handling. Hence actual testing that exception was # during request handling. Hence actual testing that exception was

View File

@ -159,7 +159,7 @@ class ImageFieldTests(ImageFieldTestMixin, TestCase):
self.assertEqual(p.mugshot.closed, True) self.assertEqual(p.mugshot.closed, True)
# After asking for the size, the file should still be closed. # After asking for the size, the file should still be closed.
_ = p.mugshot.size p.mugshot.size
self.assertEqual(p.mugshot.closed, True) self.assertEqual(p.mugshot.closed, True)
def test_pickle(self): def test_pickle(self):

View File

@ -604,7 +604,7 @@ class PromiseTest(test.TestCase):
def test_IPAddressField(self): def test_IPAddressField(self):
lazy_func = lazy(lambda: '127.0.0.1', six.text_type) lazy_func = lazy(lambda: '127.0.0.1', six.text_type)
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
self.assertIsInstance( self.assertIsInstance(
IPAddressField().get_prep_value(lazy_func()), IPAddressField().get_prep_value(lazy_func()),

View File

@ -259,7 +259,7 @@ class ModelFormBaseTest(TestCase):
['name', 'slug', 'url']) ['name', 'slug', 'url'])
def test_missing_fields_attribute(self): def test_missing_fields_attribute(self):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always", DeprecationWarning) warnings.simplefilter("always", DeprecationWarning)
class MissingFieldsForm(forms.ModelForm): class MissingFieldsForm(forms.ModelForm):
@ -429,11 +429,11 @@ class ModelFormBaseTest(TestCase):
# Can't create new form # Can't create new form
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
f = InvalidModelForm() InvalidModelForm()
# Even if you provide a model instance # Even if you provide a model instance
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
f = InvalidModelForm(instance=Category) InvalidModelForm(instance=Category)
def test_subcategory_form(self): def test_subcategory_form(self):
class SubCategoryForm(BaseCategoryForm): class SubCategoryForm(BaseCategoryForm):
@ -668,7 +668,7 @@ class UniqueTest(TestCase):
def test_abstract_inherited_unique(self): def test_abstract_inherited_unique(self):
title = 'Boss' title = 'Boss'
isbn = '12345' isbn = '12345'
dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn}) form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn})
self.assertFalse(form.is_valid()) self.assertFalse(form.is_valid())
self.assertEqual(len(form.errors), 1) self.assertEqual(len(form.errors), 1)
@ -677,7 +677,7 @@ class UniqueTest(TestCase):
def test_abstract_inherited_unique_together(self): def test_abstract_inherited_unique_together(self):
title = 'Boss' title = 'Boss'
isbn = '12345' isbn = '12345'
dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn) DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
form = DerivedBookForm({ form = DerivedBookForm({
'title': 'Other', 'title': 'Other',
'author': self.writer.pk, 'author': self.writer.pk,
@ -737,7 +737,7 @@ class UniqueTest(TestCase):
"""If the date for unique_for_* constraints is excluded from the """If the date for unique_for_* constraints is excluded from the
ModelForm (in this case 'posted' has editable=False, then the ModelForm (in this case 'posted' has editable=False, then the
constraint should be ignored.""" constraint should be ignored."""
p = DateTimePost.objects.create(title="Django 1.0 is released", DateTimePost.objects.create(title="Django 1.0 is released",
slug="Django 1.0", subtitle="Finally", slug="Django 1.0", subtitle="Finally",
posted=datetime.datetime(2008, 9, 3, 10, 10, 1)) posted=datetime.datetime(2008, 9, 3, 10, 10, 1))
# 'title' has unique_for_date='posted' # 'title' has unique_for_date='posted'
@ -1697,7 +1697,7 @@ class OldFormForXTests(TestCase):
def test_foreignkeys_which_use_to_field(self): def test_foreignkeys_which_use_to_field(self):
apple = Inventory.objects.create(barcode=86, name='Apple') apple = Inventory.objects.create(barcode=86, name='Apple')
pear = Inventory.objects.create(barcode=22, name='Pear') Inventory.objects.create(barcode=22, name='Pear')
core = Inventory.objects.create(barcode=87, name='Core', parent=apple) core = Inventory.objects.create(barcode=87, name='Core', parent=apple)
field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode') field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode')

View File

@ -369,8 +369,7 @@ class FormFieldCallbackTests(TestCase):
widgets = {'name': widget} widgets = {'name': widget}
fields = "__all__" fields = "__all__"
_ = modelform_factory(Person, form=BaseForm, modelform_factory(Person, form=BaseForm, formfield_callback=callback)
formfield_callback=callback)
id_field, name_field = Person._meta.fields id_field, name_field = Person._meta.fields
self.assertEqual(callback_args, self.assertEqual(callback_args,
@ -567,7 +566,7 @@ class TestTicket19733(TestCase):
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always", DeprecationWarning) warnings.simplefilter("always", DeprecationWarning)
# This should become an error once deprecation cycle is complete. # This should become an error once deprecation cycle is complete.
form = modelform_factory(Person) modelform_factory(Person)
self.assertEqual(w[0].category, DeprecationWarning) self.assertEqual(w[0].category, DeprecationWarning)
def test_modelform_factory_with_all_fields(self): def test_modelform_factory_with_all_fields(self):

View File

@ -291,9 +291,9 @@ class ModelFormsetTest(TestCase):
# all existing related objects/inlines for a given object to be # all existing related objects/inlines for a given object to be
# displayed, but not allow the creation of new inlines beyond max_num. # displayed, but not allow the creation of new inlines beyond max_num.
author1 = Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Charles Baudelaire')
author2 = Author.objects.create(name='Paul Verlaine') Author.objects.create(name='Paul Verlaine')
author3 = Author.objects.create(name='Walt Whitman') Author.objects.create(name='Walt Whitman')
qs = Author.objects.order_by('name') qs = Author.objects.order_by('name')
@ -394,8 +394,8 @@ class ModelFormsetTest(TestCase):
Test that a queryset can be overridden in the __init__ method. Test that a queryset can be overridden in the __init__ method.
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-queryset https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-queryset
""" """
author1 = Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Charles Baudelaire')
author2 = Author.objects.create(name='Paul Verlaine') Author.objects.create(name='Paul Verlaine')
class BaseAuthorFormSet(BaseModelFormSet): class BaseAuthorFormSet(BaseModelFormSet):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
@ -535,7 +535,7 @@ class ModelFormsetTest(TestCase):
# The save_as_new parameter lets you re-associate the data to a new # The save_as_new parameter lets you re-associate the data to a new
# instance. This is used in the admin for save_as functionality. # instance. This is used in the admin for save_as functionality.
AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__") AuthorBooksFormSet = inlineformset_factory(Author, Book, can_delete=False, extra=2, fields="__all__")
author = Author.objects.create(name='Charles Baudelaire') Author.objects.create(name='Charles Baudelaire')
data = { data = {
'book_set-TOTAL_FORMS': '3', # the number of forms rendered 'book_set-TOTAL_FORMS': '3', # the number of forms rendered
@ -1139,7 +1139,7 @@ class ModelFormsetTest(TestCase):
# has_changed should work with queryset and list of pk's # has_changed should work with queryset and list of pk's
# see #18898 # see #18898
FormSet = modelformset_factory(AuthorMeeting, fields='__all__') FormSet = modelformset_factory(AuthorMeeting, fields='__all__')
author = Author.objects.create(pk=1, name='Charles Baudelaire') Author.objects.create(pk=1, name='Charles Baudelaire')
data = { data = {
'form-TOTAL_FORMS': 1, 'form-TOTAL_FORMS': 1,
'form-INITIAL_FORMS': 0, 'form-INITIAL_FORMS': 0,
@ -1195,9 +1195,9 @@ class ModelFormsetTest(TestCase):
FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__") FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__")
author = Author.objects.create(pk=1, name='Charles Baudelaire') author = Author.objects.create(pk=1, name='Charles Baudelaire')
book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels') Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels')
book2 = Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal') Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal')
book3 = Book.objects.create(pk=3, author=author, title='Flowers of Evil') Book.objects.create(pk=3, author=author, title='Flowers of Evil')
book_ids = author.book_set.order_by('id').values_list('id', flat=True) book_ids = author.book_set.order_by('id').values_list('id', flat=True)
data = { data = {

View File

@ -161,8 +161,8 @@ class InlineFormsetTests(TestCase):
# Instantiate the Form and FormSet to prove # Instantiate the Form and FormSet to prove
# you can create a formset with an instance of None # you can create a formset with an instance of None
form = Form(instance=None) Form(instance=None)
formset = FormSet(instance=None) FormSet(instance=None)
def test_empty_fields_on_modelformset(self): def test_empty_fields_on_modelformset(self):
"No fields passed to modelformset_factory should result in no fields on returned forms except for the id. See #14119." "No fields passed to modelformset_factory should result in no fields on returned forms except for the id. See #14119."

View File

@ -133,7 +133,7 @@ class ModelInheritanceTest(TestCase):
def test_issue_7105(self): def test_issue_7105(self):
# Regressions tests for #7105: dates() queries should be able to use # Regressions tests for #7105: dates() queries should be able to use
# fields from the parent model as easily as the child. # fields from the parent model as easily as the child.
obj = Child.objects.create( Child.objects.create(
name='child', name='child',
created=datetime.datetime(2008, 6, 26, 17, 0, 0)) created=datetime.datetime(2008, 6, 26, 17, 0, 0))
datetimes = list(Child.objects.datetimes('created', 'month')) datetimes = list(Child.objects.datetimes('created', 'month'))
@ -159,7 +159,7 @@ class ModelInheritanceTest(TestCase):
ident = ItalianRestaurant.objects.all()[0].id ident = ItalianRestaurant.objects.all()[0].id
self.assertEqual(Place.objects.get(pk=ident), place1) self.assertEqual(Place.objects.get(pk=ident), place1)
xx = Restaurant.objects.create( Restaurant.objects.create(
name='a', name='a',
address='xx', address='xx',
serves_hot_dogs=True, serves_hot_dogs=True,

View File

@ -16,8 +16,8 @@ class ModelInheritanceSelectRelatedTests(TestCase):
r2 = Restaurant.objects.create( r2 = Restaurant.objects.create(
name="Craft", serves_sushi=False, serves_steak=True name="Craft", serves_sushi=False, serves_steak=True
) )
p1 = Person.objects.create(name="John", favorite_restaurant=r1) Person.objects.create(name="John", favorite_restaurant=r1)
p2 = Person.objects.create(name="Jane", favorite_restaurant=r2) Person.objects.create(name="Jane", favorite_restaurant=r2)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Person.objects.order_by("name").select_related(), [ Person.objects.order_by("name").select_related(), [

View File

@ -217,7 +217,7 @@ class ModelTests(TestCase):
class ModelValidationTest(TestCase): class ModelValidationTest(TestCase):
def test_pk_validation(self): def test_pk_validation(self):
one = NonAutoPK.objects.create(name="one") NonAutoPK.objects.create(name="one")
again = NonAutoPK(name="one") again = NonAutoPK(name="one")
self.assertRaises(ValidationError, again.validate_unique) self.assertRaises(ValidationError, again.validate_unique)

View File

@ -405,7 +405,7 @@ class ModelAdminTests(TestCase):
ConcertInline ConcertInline
] ]
concert = Concert.objects.create(main_band=self.band, opening_band=self.band, day=1) Concert.objects.create(main_band=self.band, opening_band=self.band, day=1)
ma = BandAdmin(Band, self.site) ma = BandAdmin(Band, self.site)
inline_instances = ma.get_inline_instances(request) inline_instances = ma.get_inline_instances(request)
fieldsets = list(inline_instances[0].get_fieldsets(request)) fieldsets = list(inline_instances[0].get_fieldsets(request))

View File

@ -384,14 +384,12 @@ class QueryTestCase(TestCase):
pro = Book.objects.create(title="Pro Django", pro = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
marty = Person.objects.create(name="Marty Alchin")
george = Person.objects.create(name="George Vilches") george = Person.objects.create(name="George Vilches")
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4)) published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
chris = Person.objects.using('other').create(name="Chris Mills") chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author's favourite books # Save the author's favourite books
@ -431,7 +429,6 @@ class QueryTestCase(TestCase):
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4)) published=datetime.date(2009, 5, 4))
mark = Person.objects.using('other').create(name="Mark Pilgrim")
chris = Person.objects.using('other').create(name="Chris Mills") chris = Person.objects.using('other').create(name="Chris Mills")
# Save the author relations # Save the author relations
@ -561,7 +558,7 @@ class QueryTestCase(TestCase):
def test_foreign_key_deletion(self): def test_foreign_key_deletion(self):
"Cascaded deletions of Foreign Key relations issue queries on the right database" "Cascaded deletions of Foreign Key relations issue queries on the right database"
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
fido = Pet.objects.using('other').create(name="Fido", owner=mark) Pet.objects.using('other').create(name="Fido", owner=mark)
# Check the initial state # Check the initial state
self.assertEqual(Person.objects.using('default').count(), 0) self.assertEqual(Person.objects.using('default').count(), 0)
@ -779,7 +776,7 @@ class QueryTestCase(TestCase):
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4)) published=datetime.date(2009, 5, 4))
review2 = Review.objects.using('other').create(source="Python Weekly", content_object=dive) Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Set a foreign key with an object from a different database # Set a foreign key with an object from a different database
try: try:
@ -822,7 +819,7 @@ class QueryTestCase(TestCase):
"Cascaded deletions of Generic Key relations issue queries on the right database" "Cascaded deletions of Generic Key relations issue queries on the right database"
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4)) published=datetime.date(2009, 5, 4))
review = Review.objects.using('other').create(source="Python Weekly", content_object=dive) Review.objects.using('other').create(source="Python Weekly", content_object=dive)
# Check the initial state # Check the initial state
self.assertEqual(Book.objects.using('default').count(), 0) self.assertEqual(Book.objects.using('default').count(), 0)
@ -843,7 +840,7 @@ class QueryTestCase(TestCase):
def test_ordering(self): def test_ordering(self):
"get_next_by_XXX commands stick to a single database" "get_next_by_XXX commands stick to a single database"
pro = Book.objects.create(title="Pro Django", Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
dive = Book.objects.using('other').create(title="Dive into Python", dive = Book.objects.using('other').create(title="Dive into Python",
@ -869,9 +866,9 @@ class QueryTestCase(TestCase):
"Database assignment is retained if an object is retrieved with select_related()" "Database assignment is retained if an object is retrieved with select_related()"
# Create a book and author on the other database # Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
dive = Book.objects.using('other').create(title="Dive into Python", Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4), published=datetime.date(2009, 5, 4),
editor=mark) editor=mark)
# Retrieve the Person using select_related() # Retrieve the Person using select_related()
book = Book.objects.using('other').select_related('editor').get(title="Dive into Python") book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
@ -1033,8 +1030,8 @@ class RouterTestCase(TestCase):
pro.authors = [marty] pro.authors = [marty]
# Create a book and author on the other database # Create a book and author on the other database
dive = Book.objects.using('other').create(title="Dive into Python", Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4)) published=datetime.date(2009, 5, 4))
# An update query will be routed to the default database # An update query will be routed to the default database
Book.objects.filter(title='Pro Django').update(pages=200) Book.objects.filter(title='Pro Django').update(pages=200)
@ -1443,8 +1440,6 @@ class RouterTestCase(TestCase):
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
pro_authors = pro.authors.using('other')
authors = [marty]
self.assertEqual(pro.authors.db, 'other') self.assertEqual(pro.authors.db, 'other')
self.assertEqual(pro.authors.db_manager('default').db, 'default') self.assertEqual(pro.authors.db_manager('default').db, 'default')
@ -1457,9 +1452,9 @@ class RouterTestCase(TestCase):
def test_foreign_key_managers(self): def test_foreign_key_managers(self):
"FK reverse relations are represented by managers, and can be controlled like managers" "FK reverse relations are represented by managers, and can be controlled like managers"
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin") marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
pro = Book.objects.using('other').create(pk=1, title="Pro Django", Book.objects.using('other').create(pk=1, title="Pro Django",
published=datetime.date(2008, 12, 16), published=datetime.date(2008, 12, 16),
editor=marty) editor=marty)
self.assertEqual(marty.edited.db, 'other') self.assertEqual(marty.edited.db, 'other')
self.assertEqual(marty.edited.db_manager('default').db, 'default') self.assertEqual(marty.edited.db_manager('default').db, 'default')
@ -1470,8 +1465,8 @@ class RouterTestCase(TestCase):
pro = Book.objects.using('other').create(title="Pro Django", pro = Book.objects.using('other').create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
review1 = Review.objects.using('other').create(source="Python Monthly", Review.objects.using('other').create(source="Python Monthly",
content_object=pro) content_object=pro)
self.assertEqual(pro.reviews.db, 'other') self.assertEqual(pro.reviews.db, 'other')
self.assertEqual(pro.reviews.db_manager('default').db, 'default') self.assertEqual(pro.reviews.db_manager('default').db, 'default')
@ -1482,9 +1477,9 @@ class RouterTestCase(TestCase):
# Create a book and author on the other database # Create a book and author on the other database
mark = Person.objects.using('other').create(name="Mark Pilgrim") mark = Person.objects.using('other').create(name="Mark Pilgrim")
dive = Book.objects.using('other').create(title="Dive into Python", Book.objects.using('other').create(title="Dive into Python",
published=datetime.date(2009, 5, 4), published=datetime.date(2009, 5, 4),
editor=mark) editor=mark)
sub = Person.objects.filter(name='Mark Pilgrim') sub = Person.objects.filter(name='Mark Pilgrim')
qs = Book.objects.filter(editor__in=sub) qs = Book.objects.filter(editor__in=sub)
@ -1857,7 +1852,7 @@ class RouterModelArgumentTestCase(TestCase):
def test_foreignkey_collection(self): def test_foreignkey_collection(self):
person = Person.objects.create(name='Bob') person = Person.objects.create(name='Bob')
pet = Pet.objects.create(owner=person, name='Wart') Pet.objects.create(owner=person, name='Wart')
# test related FK collection # test related FK collection
person.delete() person.delete()
@ -1967,7 +1962,7 @@ class RouteForWriteTestCase(TestCase):
def test_reverse_fk_update(self): def test_reverse_fk_update(self):
owner = Person.objects.create(name='Someone') owner = Person.objects.create(name='Someone')
pet = Pet.objects.create(name='fido', owner=owner) Pet.objects.create(name='fido', owner=owner)
self.enable_router() self.enable_router()
try: try:
owner.pet_set.update(name='max') owner.pet_set.update(name='max')
@ -2019,7 +2014,7 @@ class RouteForWriteTestCase(TestCase):
self.assertEqual(e.hints, {'instance': book}) self.assertEqual(e.hints, {'instance': book})
def test_m2m_get_or_create(self): def test_m2m_get_or_create(self):
auth = Person.objects.create(name='Someone') Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django", book = Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
self.enable_router() self.enable_router()
@ -2103,8 +2098,8 @@ class RouteForWriteTestCase(TestCase):
def test_reverse_m2m_get_or_create(self): def test_reverse_m2m_get_or_create(self):
auth = Person.objects.create(name='Someone') auth = Person.objects.create(name='Someone')
book = Book.objects.create(title="Pro Django", Book.objects.create(title="Pro Django",
published=datetime.date(2008, 12, 16)) published=datetime.date(2008, 12, 16))
self.enable_router() self.enable_router()
try: try:
auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now()) auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now())

View File

@ -12,7 +12,7 @@ class MutuallyReferentialTests(TestCase):
# Create some children # Create some children
c = q.child_set.create(name='Charles') c = q.child_set.create(name='Charles')
e = q.child_set.create(name='Edward') q.child_set.create(name='Edward')
# Set the best child # Set the best child
# No assertion require here; if basic assignment and # No assertion require here; if basic assignment and

View File

@ -32,8 +32,8 @@ class NestedForeignKeysTests(TestCase):
# This test failed in #16715 because in some cases INNER JOIN was selected # This test failed in #16715 because in some cases INNER JOIN was selected
# for the second foreign key relation instead of LEFT OUTER JOIN. # for the second foreign key relation instead of LEFT OUTER JOIN.
def testInheritance(self): def testInheritance(self):
some_event = Event.objects.create() Event.objects.create()
screening = Screening.objects.create(movie=self.movie) Screening.objects.create(movie=self.movie)
self.assertEqual(len(Event.objects.all()), 2) self.assertEqual(len(Event.objects.all()), 2)
self.assertEqual(len(Event.objects.select_related('screening')), 2) self.assertEqual(len(Event.objects.select_related('screening')), 2)
@ -53,9 +53,9 @@ class NestedForeignKeysTests(TestCase):
# These all work because the second foreign key in the chain has null=True. # These all work because the second foreign key in the chain has null=True.
def testInheritanceNullFK(self): def testInheritanceNullFK(self):
some_event = Event.objects.create() Event.objects.create()
screening = ScreeningNullFK.objects.create(movie=None) ScreeningNullFK.objects.create(movie=None)
screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie) ScreeningNullFK.objects.create(movie=self.movie)
self.assertEqual(len(Event.objects.all()), 3) self.assertEqual(len(Event.objects.all()), 3)
self.assertEqual(len(Event.objects.select_related('screeningnullfk')), 3) self.assertEqual(len(Event.objects.select_related('screeningnullfk')), 3)
@ -80,9 +80,9 @@ class NestedForeignKeysTests(TestCase):
# This test failed in #16715 because in some cases INNER JOIN was selected # This test failed in #16715 because in some cases INNER JOIN was selected
# for the second foreign key relation instead of LEFT OUTER JOIN. # for the second foreign key relation instead of LEFT OUTER JOIN.
def testExplicitForeignKey(self): def testExplicitForeignKey(self):
package = Package.objects.create() Package.objects.create()
screening = Screening.objects.create(movie=self.movie) screening = Screening.objects.create(movie=self.movie)
package_with_screening = Package.objects.create(screening=screening) Package.objects.create(screening=screening)
self.assertEqual(len(Package.objects.all()), 2) self.assertEqual(len(Package.objects.all()), 2)
self.assertEqual(len(Package.objects.select_related('screening')), 2) self.assertEqual(len(Package.objects.select_related('screening')), 2)
@ -100,11 +100,11 @@ class NestedForeignKeysTests(TestCase):
# These all work because the second foreign key in the chain has null=True. # These all work because the second foreign key in the chain has null=True.
def testExplicitForeignKeyNullFK(self): def testExplicitForeignKeyNullFK(self):
package = PackageNullFK.objects.create() PackageNullFK.objects.create()
screening = ScreeningNullFK.objects.create(movie=None) screening = ScreeningNullFK.objects.create(movie=None)
screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie) screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie)
package_with_screening = PackageNullFK.objects.create(screening=screening) PackageNullFK.objects.create(screening=screening)
package_with_screening_with_movie = PackageNullFK.objects.create(screening=screening_with_movie) PackageNullFK.objects.create(screening=screening_with_movie)
self.assertEqual(len(PackageNullFK.objects.all()), 3) self.assertEqual(len(PackageNullFK.objects.all()), 3)
self.assertEqual(len(PackageNullFK.objects.select_related('screening')), 3) self.assertEqual(len(PackageNullFK.objects.select_related('screening')), 3)
@ -129,8 +129,8 @@ class DeeplyNestedForeignKeysTests(TestCase):
self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director) self.movie = Movie.objects.create(title='Monty Python and the Holy Grail', director=self.director)
def testInheritance(self): def testInheritance(self):
some_event = Event.objects.create() Event.objects.create()
screening = Screening.objects.create(movie=self.movie) Screening.objects.create(movie=self.movie)
self.assertEqual(len(Event.objects.all()), 2) self.assertEqual(len(Event.objects.all()), 2)
self.assertEqual(len(Event.objects.select_related('screening__movie__director')), 2) self.assertEqual(len(Event.objects.select_related('screening__movie__director')), 2)
@ -148,9 +148,9 @@ class DeeplyNestedForeignKeysTests(TestCase):
self.assertEqual(Event.objects.exclude(screening__movie__director=self.director).count(), 1) self.assertEqual(Event.objects.exclude(screening__movie__director=self.director).count(), 1)
def testExplicitForeignKey(self): def testExplicitForeignKey(self):
package = Package.objects.create() Package.objects.create()
screening = Screening.objects.create(movie=self.movie) screening = Screening.objects.create(movie=self.movie)
package_with_screening = Package.objects.create(screening=screening) Package.objects.create(screening=screening)
self.assertEqual(len(Package.objects.all()), 2) self.assertEqual(len(Package.objects.all()), 2)
self.assertEqual(len(Package.objects.select_related('screening__movie__director')), 2) self.assertEqual(len(Package.objects.select_related('screening__movie__director')), 2)

View File

@ -15,9 +15,9 @@ class NullFkOrderingTests(TestCase):
""" """
author_1 = Author.objects.create(name='Tom Jones') author_1 = Author.objects.create(name='Tom Jones')
author_2 = Author.objects.create(name='Bob Smith') author_2 = Author.objects.create(name='Bob Smith')
article_1 = Article.objects.create(title='No author on this article') Article.objects.create(title='No author on this article')
article_2 = Article.objects.create(author=author_1, title='This article written by Tom Jones') Article.objects.create(author=author_1, title='This article written by Tom Jones')
article_3 = Article.objects.create(author=author_2, title='This article written by Bob Smith') Article.objects.create(author=author_2, title='This article written by Bob Smith')
# We can't compare results directly (since different databases sort NULLs to # We can't compare results directly (since different databases sort NULLs to
# different ends of the ordering), but we can check that all results are # different ends of the ordering), but we can check that all results are
@ -27,13 +27,13 @@ class NullFkOrderingTests(TestCase):
s = SystemInfo.objects.create(system_name='System Info') s = SystemInfo.objects.create(system_name='System Info')
f = Forum.objects.create(system_info=s, forum_name='First forum') f = Forum.objects.create(system_info=s, forum_name='First forum')
p = Post.objects.create(forum=f, title='First Post') p = Post.objects.create(forum=f, title='First Post')
c1 = Comment.objects.create(post=p, comment_text='My first comment') Comment.objects.create(post=p, comment_text='My first comment')
c2 = Comment.objects.create(comment_text='My second comment') Comment.objects.create(comment_text='My second comment')
s2 = SystemInfo.objects.create(system_name='More System Info') s2 = SystemInfo.objects.create(system_name='More System Info')
f2 = Forum.objects.create(system_info=s2, forum_name='Second forum') f2 = Forum.objects.create(system_info=s2, forum_name='Second forum')
p2 = Post.objects.create(forum=f2, title='Second Post') p2 = Post.objects.create(forum=f2, title='Second Post')
c3 = Comment.objects.create(comment_text='Another first comment') Comment.objects.create(comment_text='Another first comment')
c4 = Comment.objects.create(post=p2, comment_text='Another second comment') Comment.objects.create(post=p2, comment_text='Another second comment')
# We have to test this carefully. Some databases sort NULL values before # We have to test this carefully. Some databases sort NULL values before
# everything else, some sort them afterwards. So we extract the ordered list # everything else, some sort them afterwards. So we extract the ordered list

View File

@ -63,7 +63,7 @@ class NullQueriesTests(TestCase):
['<OuterA: OuterA object>'] ['<OuterA: OuterA object>']
) )
inner_obj = Inner.objects.create(first=obj) Inner.objects.create(first=obj)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Inner.objects.filter(first__inner__third=None), Inner.objects.filter(first__inner__third=None),
['<Inner: Inner object>'] ['<Inner: Inner object>']
@ -71,7 +71,7 @@ class NullQueriesTests(TestCase):
# Ticket #13815: check if <reverse>_isnull=False does not produce # Ticket #13815: check if <reverse>_isnull=False does not produce
# faulty empty lists # faulty empty lists
objB = OuterB.objects.create(data="reverse") OuterB.objects.create(data="reverse")
self.assertQuerysetEqual( self.assertQuerysetEqual(
OuterB.objects.filter(inner__isnull=False), OuterB.objects.filter(inner__isnull=False),
[] []

View File

@ -68,6 +68,6 @@ class OrderWithRespectToTests(TestCase):
p2 = Post.objects.create(title='2') p2 = Post.objects.create(title='2')
p1_1 = Post.objects.create(title="1.1", parent=p1) p1_1 = Post.objects.create(title="1.1", parent=p1)
p1_2 = Post.objects.create(title="1.2", parent=p1) p1_2 = Post.objects.create(title="1.2", parent=p1)
p2_1 = Post.objects.create(title="2.1", parent=p2) Post.objects.create(title="2.1", parent=p2)
p1_3 = Post.objects.create(title="1.3", parent=p1) p1_3 = Post.objects.create(title="1.3", parent=p1)
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk]) self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])

View File

@ -10,13 +10,13 @@ from .models import Article, ArticlePKOrdering
class OrderingTests(TestCase): class OrderingTests(TestCase):
def test_basic(self): def test_basic(self):
a1 = Article.objects.create( Article.objects.create(
headline="Article 1", pub_date=datetime(2005, 7, 26) headline="Article 1", pub_date=datetime(2005, 7, 26)
) )
a2 = Article.objects.create( Article.objects.create(
headline="Article 2", pub_date=datetime(2005, 7, 27) headline="Article 2", pub_date=datetime(2005, 7, 27)
) )
a3 = Article.objects.create( Article.objects.create(
headline="Article 3", pub_date=datetime(2005, 7, 27) headline="Article 3", pub_date=datetime(2005, 7, 27)
) )
a4 = Article.objects.create( a4 = Article.objects.create(
@ -143,16 +143,16 @@ class OrderingTests(TestCase):
Ensure that 'pk' works as an ordering option in Meta. Ensure that 'pk' works as an ordering option in Meta.
Refs #8291. Refs #8291.
""" """
a1 = ArticlePKOrdering.objects.create( ArticlePKOrdering.objects.create(
pk=1, headline="Article 1", pub_date=datetime(2005, 7, 26) pk=1, headline="Article 1", pub_date=datetime(2005, 7, 26)
) )
a2 = ArticlePKOrdering.objects.create( ArticlePKOrdering.objects.create(
pk=2, headline="Article 2", pub_date=datetime(2005, 7, 27) pk=2, headline="Article 2", pub_date=datetime(2005, 7, 27)
) )
a3 = ArticlePKOrdering.objects.create( ArticlePKOrdering.objects.create(
pk=3, headline="Article 3", pub_date=datetime(2005, 7, 27) pk=3, headline="Article 3", pub_date=datetime(2005, 7, 27)
) )
a4 = ArticlePKOrdering.objects.create( ArticlePKOrdering.objects.create(
pk=4, headline="Article 4", pub_date=datetime(2005, 7, 28) pk=4, headline="Article 4", pub_date=datetime(2005, 7, 28)
) )

View File

@ -64,8 +64,8 @@ class PrefetchRelatedTests(TestCase):
def test_foreignkey_reverse(self): def test_foreignkey_reverse(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
lists = [list(b.first_time_authors.all()) [list(b.first_time_authors.all())
for b in Book.objects.prefetch_related('first_time_authors')] for b in Book.objects.prefetch_related('first_time_authors')]
self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"]) self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"])
@ -79,22 +79,20 @@ class PrefetchRelatedTests(TestCase):
def test_survives_clone(self): def test_survives_clone(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
lists = [list(b.first_time_authors.all()) [list(b.first_time_authors.all())
for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)] for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)]
def test_len(self): def test_len(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors') qs = Book.objects.prefetch_related('first_time_authors')
length = len(qs) len(qs)
lists = [list(b.first_time_authors.all()) [list(b.first_time_authors.all()) for b in qs]
for b in qs]
def test_bool(self): def test_bool(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
qs = Book.objects.prefetch_related('first_time_authors') qs = Book.objects.prefetch_related('first_time_authors')
x = bool(qs) bool(qs)
lists = [list(b.first_time_authors.all()) [list(b.first_time_authors.all()) for b in qs]
for b in qs]
def test_count(self): def test_count(self):
with self.assertNumQueries(2): with self.assertNumQueries(2):
@ -123,7 +121,7 @@ class PrefetchRelatedTests(TestCase):
with self.assertNumQueries(5): with self.assertNumQueries(5):
with_prefetch = Author.objects.prefetch_related('books') with_prefetch = Author.objects.prefetch_related('books')
without_prefetch = with_prefetch.prefetch_related(None) without_prefetch = with_prefetch.prefetch_related(None)
lists = [list(a.books.all()) for a in without_prefetch] [list(a.books.all()) for a in without_prefetch]
def test_m2m_then_m2m(self): def test_m2m_then_m2m(self):
""" """
@ -321,8 +319,8 @@ class GenericRelationTests(TestCase):
def test_generic_relation(self): def test_generic_relation(self):
bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/') bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
t1 = TaggedItem.objects.create(content_object=bookmark, tag='django') TaggedItem.objects.create(content_object=bookmark, tag='django')
t2 = TaggedItem.objects.create(content_object=bookmark, tag='python') TaggedItem.objects.create(content_object=bookmark, tag='python')
with self.assertNumQueries(2): with self.assertNumQueries(2):
tags = [t.tag for b in Bookmark.objects.prefetch_related('tags') tags = [t.tag for b in Bookmark.objects.prefetch_related('tags')
@ -331,8 +329,8 @@ class GenericRelationTests(TestCase):
def test_charfield_GFK(self): def test_charfield_GFK(self):
b = Bookmark.objects.create(url='http://www.djangoproject.com/') b = Bookmark.objects.create(url='http://www.djangoproject.com/')
t1 = TaggedItem.objects.create(content_object=b, tag='django') TaggedItem.objects.create(content_object=b, tag='django')
t2 = TaggedItem.objects.create(content_object=b, favorite=b, tag='python') TaggedItem.objects.create(content_object=b, favorite=b, tag='python')
with self.assertNumQueries(3): with self.assertNumQueries(3):
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0] bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
@ -497,8 +495,8 @@ class NullableTest(TestCase):
def setUp(self): def setUp(self):
boss = Employee.objects.create(name="Peter") boss = Employee.objects.create(name="Peter")
worker1 = Employee.objects.create(name="Joe", boss=boss) Employee.objects.create(name="Joe", boss=boss)
worker2 = Employee.objects.create(name="Angela", boss=boss) Employee.objects.create(name="Angela", boss=boss)
def test_traverse_nullable(self): def test_traverse_nullable(self):
# Because we use select_related() for 'boss', it doesn't need to be # Because we use select_related() for 'boss', it doesn't need to be
@ -592,8 +590,8 @@ class MultiDbTests(TestCase):
book1 = B.create(title="Poems") book1 = B.create(title="Poems")
book2 = B.create(title="Sense and Sensibility") book2 = B.create(title="Sense and Sensibility")
author1 = A.create(name="Charlotte Bronte", first_book=book1) A.create(name="Charlotte Bronte", first_book=book1)
author2 = A.create(name="Jane Austen", first_book=book2) A.create(name="Jane Austen", first_book=book2)
# Forward # Forward
with self.assertNumQueries(2, using='other'): with self.assertNumQueries(2, using='other'):
@ -613,9 +611,9 @@ class MultiDbTests(TestCase):
B = BookWithYear.objects.using('other') B = BookWithYear.objects.using('other')
A = AuthorWithAge.objects.using('other') A = AuthorWithAge.objects.using('other')
book1 = B.create(title="Poems", published_year=2010) book1 = B.create(title="Poems", published_year=2010)
book2 = B.create(title="More poems", published_year=2011) B.create(title="More poems", published_year=2011)
author1 = A.create(name='Jane', first_book=book1, age=50) A.create(name='Jane', first_book=book1, age=50)
author2 = A.create(name='Tom', first_book=book1, age=49) A.create(name='Tom', first_book=book1, age=49)
# parent link # parent link
with self.assertNumQueries(2, using='other'): with self.assertNumQueries(2, using='other'):

View File

@ -105,8 +105,8 @@ class ProxyModelTests(TestCase):
name='Zathras' name='Zathras'
) )
sp1 = StatusPerson.objects.create(name='Bazza Jr.') StatusPerson.objects.create(name='Bazza Jr.')
sp2 = StatusPerson.objects.create(name='Foo Jr.') StatusPerson.objects.create(name='Foo Jr.')
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id'] max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
self.assertRaises(Person.MultipleObjectsReturned, self.assertRaises(Person.MultipleObjectsReturned,
@ -232,7 +232,7 @@ class ProxyModelTests(TestCase):
signals.pre_save.connect(h3, sender=Person) signals.pre_save.connect(h3, sender=Person)
signals.post_save.connect(h4, sender=Person) signals.post_save.connect(h4, sender=Person)
dino = MyPerson.objects.create(name="dino") MyPerson.objects.create(name="dino")
self.assertEqual(output, [ self.assertEqual(output, [
'MyPerson pre save', 'MyPerson pre save',
'MyPerson post save' 'MyPerson post save'
@ -246,7 +246,7 @@ class ProxyModelTests(TestCase):
signals.pre_save.connect(h5, sender=MyPersonProxy) signals.pre_save.connect(h5, sender=MyPersonProxy)
signals.post_save.connect(h6, sender=MyPersonProxy) signals.post_save.connect(h6, sender=MyPersonProxy)
dino = MyPersonProxy.objects.create(name="pebbles") MyPersonProxy.objects.create(name="pebbles")
self.assertEqual(output, [ self.assertEqual(output, [
'MyPersonProxy pre save', 'MyPersonProxy pre save',
@ -303,7 +303,7 @@ class ProxyModelTests(TestCase):
querysets. querysets.
""" """
country = Country.objects.create(name='Australia') country = Country.objects.create(name='Australia')
state = State.objects.create(name='New South Wales', country=country) State.objects.create(name='New South Wales', country=country)
resp = [s.name for s in State.objects.select_related()] resp = [s.name for s in State.objects.select_related()]
self.assertEqual(resp, ['New South Wales']) self.assertEqual(resp, ['New South Wales'])

View File

@ -713,7 +713,7 @@ class Queries1Tests(BaseQuerysetTest):
# Pickling of DateQuerySets used to fail # Pickling of DateQuerySets used to fail
qs = Item.objects.datetimes('created', 'month') qs = Item.objects.datetimes('created', 'month')
_ = pickle.loads(pickle.dumps(qs)) pickle.loads(pickle.dumps(qs))
def test_ticket9997(self): def test_ticket9997(self):
# If a ValuesList or Values queryset is passed as an inner query, we # If a ValuesList or Values queryset is passed as an inner query, we
@ -1383,7 +1383,7 @@ class Queries4Tests(BaseQuerysetTest):
c3 = SpecialCategory.objects.create(name="named category2", c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2") special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) ci2 = CategoryItem.objects.create(category=c2)
ci3 = CategoryItem.objects.create(category=c3) ci3 = CategoryItem.objects.create(category=c3)
@ -1399,8 +1399,8 @@ class Queries4Tests(BaseQuerysetTest):
special_name="special2") special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) ci1 = CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c2)
ci3 = CategoryItem.objects.create(category=c3) CategoryItem.objects.create(category=c3)
qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False) qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False)
self.assertEqual(qs.count(), 1) self.assertEqual(qs.count(), 1)
@ -1414,8 +1414,8 @@ class Queries4Tests(BaseQuerysetTest):
special_name="special2") special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) ci1 = CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) CategoryItem.objects.create(category=c2)
ci3 = CategoryItem.objects.create(category=c3) CategoryItem.objects.create(category=c3)
qs = CategoryItem.objects.filter(category__specialcategory__isnull=True) qs = CategoryItem.objects.filter(category__specialcategory__isnull=True)
self.assertEqual(qs.count(), 1) self.assertEqual(qs.count(), 1)
@ -1428,7 +1428,7 @@ class Queries4Tests(BaseQuerysetTest):
c3 = SpecialCategory.objects.create(name="named category2", c3 = SpecialCategory.objects.create(name="named category2",
special_name="special2") special_name="special2")
ci1 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
ci2 = CategoryItem.objects.create(category=c2) ci2 = CategoryItem.objects.create(category=c2)
ci3 = CategoryItem.objects.create(category=c3) ci3 = CategoryItem.objects.create(category=c3)
@ -1441,10 +1441,10 @@ class Queries4Tests(BaseQuerysetTest):
c0 = SimpleCategory.objects.create(name="cat0") c0 = SimpleCategory.objects.create(name="cat0")
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1") OneToOneCategory.objects.create(category = c1, new_name="new1")
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2") OneToOneCategory.objects.create(category = c0, new_name="new2")
ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c)
ci2 = CategoryItem.objects.create(category=c0) ci2 = CategoryItem.objects.create(category=c0)
ci3 = CategoryItem.objects.create(category=c1) ci3 = CategoryItem.objects.create(category=c1)
@ -1457,12 +1457,12 @@ class Queries4Tests(BaseQuerysetTest):
c0 = SimpleCategory.objects.create(name="cat0") c0 = SimpleCategory.objects.create(name="cat0")
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1") OneToOneCategory.objects.create(category = c1, new_name="new1")
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2") OneToOneCategory.objects.create(category = c0, new_name="new2")
ci1 = CategoryItem.objects.create(category=c) ci1 = CategoryItem.objects.create(category=c)
ci2 = CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c0)
ci3 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False) qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False)
self.assertEqual(qs.count(), 1) self.assertEqual(qs.count(), 1)
@ -1473,12 +1473,12 @@ class Queries4Tests(BaseQuerysetTest):
c0 = SimpleCategory.objects.create(name="cat0") c0 = SimpleCategory.objects.create(name="cat0")
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1") OneToOneCategory.objects.create(category = c1, new_name="new1")
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2") OneToOneCategory.objects.create(category = c0, new_name="new2")
ci1 = CategoryItem.objects.create(category=c) ci1 = CategoryItem.objects.create(category=c)
ci2 = CategoryItem.objects.create(category=c0) CategoryItem.objects.create(category=c0)
ci3 = CategoryItem.objects.create(category=c1) CategoryItem.objects.create(category=c1)
qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True) qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True)
self.assertEqual(qs.count(), 1) self.assertEqual(qs.count(), 1)
@ -1489,10 +1489,10 @@ class Queries4Tests(BaseQuerysetTest):
c0 = SimpleCategory.objects.create(name="cat0") c0 = SimpleCategory.objects.create(name="cat0")
c1 = SimpleCategory.objects.create(name="category1") c1 = SimpleCategory.objects.create(name="category1")
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1") OneToOneCategory.objects.create(category = c1, new_name="new1")
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2") OneToOneCategory.objects.create(category = c0, new_name="new2")
ci1 = CategoryItem.objects.create(category=c) CategoryItem.objects.create(category=c)
ci2 = CategoryItem.objects.create(category=c0) ci2 = CategoryItem.objects.create(category=c0)
ci3 = CategoryItem.objects.create(category=c1) ci3 = CategoryItem.objects.create(category=c1)
@ -1712,14 +1712,14 @@ class Queries6Tests(TestCase):
def setUp(self): def setUp(self):
generic = NamedCategory.objects.create(name="Generic") generic = NamedCategory.objects.create(name="Generic")
t1 = Tag.objects.create(name='t1', category=generic) t1 = Tag.objects.create(name='t1', category=generic)
t2 = Tag.objects.create(name='t2', parent=t1, category=generic) Tag.objects.create(name='t2', parent=t1, category=generic)
t3 = Tag.objects.create(name='t3', parent=t1) t3 = Tag.objects.create(name='t3', parent=t1)
t4 = Tag.objects.create(name='t4', parent=t3) t4 = Tag.objects.create(name='t4', parent=t3)
t5 = Tag.objects.create(name='t5', parent=t3) Tag.objects.create(name='t5', parent=t3)
n1 = Note.objects.create(note='n1', misc='foo', id=1) n1 = Note.objects.create(note='n1', misc='foo', id=1)
ann1 = Annotation.objects.create(name='a1', tag=t1) ann1 = Annotation.objects.create(name='a1', tag=t1)
ann1.notes.add(n1) ann1.notes.add(n1)
ann2 = Annotation.objects.create(name='a2', tag=t4) Annotation.objects.create(name='a2', tag=t4)
def test_parallel_iterators(self): def test_parallel_iterators(self):
# Test that parallel iterators work. # Test that parallel iterators work.
@ -1794,7 +1794,7 @@ class Queries6Tests(TestCase):
class RawQueriesTests(TestCase): class RawQueriesTests(TestCase):
def setUp(self): def setUp(self):
n1 = Note.objects.create(note='n1', misc='foo', id=1) Note.objects.create(note='n1', misc='foo', id=1)
def test_ticket14729(self): def test_ticket14729(self):
# Test representation of raw query with one or few parameters passed as list # Test representation of raw query with one or few parameters passed as list
@ -1827,8 +1827,8 @@ class ComparisonTests(TestCase):
def test_ticket8597(self): def test_ticket8597(self):
# Regression tests for case-insensitive comparisons # Regression tests for case-insensitive comparisons
_ = Item.objects.create(name="a_b", created=datetime.datetime.now(), creator=self.a2, note=self.n1) Item.objects.create(name="a_b", created=datetime.datetime.now(), creator=self.a2, note=self.n1)
_ = Item.objects.create(name="x%y", created=datetime.datetime.now(), creator=self.a2, note=self.n1) Item.objects.create(name="x%y", created=datetime.datetime.now(), creator=self.a2, note=self.n1)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Item.objects.filter(name__iexact="A_b"), Item.objects.filter(name__iexact="A_b"),
['<Item: a_b>'] ['<Item: a_b>']
@ -2129,7 +2129,7 @@ class WeirdQuerysetSlicingTests(BaseQuerysetTest):
class EscapingTests(TestCase): class EscapingTests(TestCase):
def test_ticket_7302(self): def test_ticket_7302(self):
# Reserved names are appropriately escaped # Reserved names are appropriately escaped
_ = ReservedName.objects.create(name='a', order=42) ReservedName.objects.create(name='a', order=42)
ReservedName.objects.create(name='b', order=37) ReservedName.objects.create(name='b', order=37)
self.assertQuerysetEqual( self.assertQuerysetEqual(
ReservedName.objects.all().order_by('order'), ReservedName.objects.all().order_by('order'),
@ -2209,10 +2209,10 @@ class ConditionalTests(BaseQuerysetTest):
def setUp(self): def setUp(self):
generic = NamedCategory.objects.create(name="Generic") generic = NamedCategory.objects.create(name="Generic")
t1 = Tag.objects.create(name='t1', category=generic) t1 = Tag.objects.create(name='t1', category=generic)
t2 = Tag.objects.create(name='t2', parent=t1, category=generic) Tag.objects.create(name='t2', parent=t1, category=generic)
t3 = Tag.objects.create(name='t3', parent=t1) t3 = Tag.objects.create(name='t3', parent=t1)
t4 = Tag.objects.create(name='t4', parent=t3) Tag.objects.create(name='t4', parent=t3)
t5 = Tag.objects.create(name='t5', parent=t3) Tag.objects.create(name='t5', parent=t3)
def test_infinite_loop(self): def test_infinite_loop(self):
# If you're not careful, it's possible to introduce infinite loops via # If you're not careful, it's possible to introduce infinite loops via
@ -2474,8 +2474,8 @@ class Exclude15786(TestCase):
def test_ticket15786(self): def test_ticket15786(self):
c1 = SimpleCategory.objects.create(name='c1') c1 = SimpleCategory.objects.create(name='c1')
c2 = SimpleCategory.objects.create(name='c2') c2 = SimpleCategory.objects.create(name='c2')
o2o1 = OneToOneCategory.objects.create(category=c1) OneToOneCategory.objects.create(category=c1)
o2o2 = OneToOneCategory.objects.create(category=c2) OneToOneCategory.objects.create(category=c2)
rel = CategoryRelationship.objects.create(first=c1, second=c2) rel = CategoryRelationship.objects.create(first=c1, second=c2)
self.assertEqual( self.assertEqual(
CategoryRelationship.objects.exclude( CategoryRelationship.objects.exclude(

View File

@ -390,7 +390,7 @@ class RequestsTests(SimpleTestCase):
'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': payload}) 'wsgi.input': payload})
raw_data = request.body request.body # evaluate
self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.POST, {'name': ['value']})
def test_POST_after_body_read_and_stream_read(self): def test_POST_after_body_read_and_stream_read(self):
@ -403,7 +403,7 @@ class RequestsTests(SimpleTestCase):
'CONTENT_TYPE': 'application/x-www-form-urlencoded', 'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': payload}) 'wsgi.input': payload})
raw_data = request.body request.body # evaluate
self.assertEqual(request.read(1), b'n') self.assertEqual(request.read(1), b'n')
self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.POST, {'name': ['value']})
@ -423,7 +423,7 @@ class RequestsTests(SimpleTestCase):
'CONTENT_TYPE': 'multipart/form-data; boundary=boundary', 'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
'CONTENT_LENGTH': len(payload), 'CONTENT_LENGTH': len(payload),
'wsgi.input': payload}) 'wsgi.input': payload})
raw_data = request.body request.body # evaluate
# Consume enough data to mess up the parsing: # Consume enough data to mess up the parsing:
self.assertEqual(request.read(13), b'--boundary\r\nC') self.assertEqual(request.read(13), b'--boundary\r\nC')
self.assertEqual(request.POST, {'name': ['value']}) self.assertEqual(request.POST, {'name': ['value']})

View File

@ -10,10 +10,10 @@ from .models import Thing
class ReservedNameTests(TestCase): class ReservedNameTests(TestCase):
def generate(self): def generate(self):
day1 = datetime.date(2005, 1, 1) day1 = datetime.date(2005, 1, 1)
t = Thing.objects.create(when='a', join='b', like='c', drop='d', Thing.objects.create(when='a', join='b', like='c', drop='d',
alter='e', having='f', where=day1, has_hyphen='h') alter='e', having='f', where=day1, has_hyphen='h')
day2 = datetime.date(2006, 2, 2) day2 = datetime.date(2006, 2, 2)
u = Thing.objects.create(when='h', join='i', like='j', drop='k', Thing.objects.create(when='h', join='i', like='j', drop='k',
alter='l', having='m', where=day2) alter='l', having='m', where=day2)
def test_simple(self): def test_simple(self):

View File

@ -19,7 +19,7 @@ class ReverseLookupTests(TestCase):
question="What's the second question?", question="What's the second question?",
creator=jim creator=jim
) )
new_choice = Choice.objects.create( Choice.objects.create(
poll=first_poll, poll=first_poll,
related_poll=second_poll, related_poll=second_poll,
name="This is the answer." name="This is the answer."

View File

@ -655,7 +655,7 @@ class SchemaTests(TransactionTestCase):
class SomeError(Exception): class SomeError(Exception):
pass pass
try: try:
with connection.schema_editor() as editor: with connection.schema_editor():
raise SomeError raise SomeError
except SomeError: except SomeError:
self.assertFalse(connection.in_atomic_block) self.assertFalse(connection.in_atomic_block)

View File

@ -254,7 +254,7 @@ class SelectForUpdateTests(TransactionTestCase):
means that it will be either committed or rolled back by Django, means that it will be either committed or rolled back by Django,
which will release any locks held by the SELECT FOR UPDATE. which will release any locks held by the SELECT FOR UPDATE.
""" """
people = list(Person.objects.select_for_update()) list(Person.objects.select_for_update())
self.assertTrue(transaction.is_dirty()) self.assertTrue(transaction.is_dirty())
@skipUnlessDBFeature('has_select_for_update') @skipUnlessDBFeature('has_select_for_update')

View File

@ -12,12 +12,11 @@ from .models import (User, UserProfile, UserStat, UserStatResult, StatDetails,
class ReverseSelectRelatedTestCase(TestCase): class ReverseSelectRelatedTestCase(TestCase):
def setUp(self): def setUp(self):
user = User.objects.create(username="test") user = User.objects.create(username="test")
userprofile = UserProfile.objects.create(user=user, state="KS", UserProfile.objects.create(user=user, state="KS", city="Lawrence")
city="Lawrence")
results = UserStatResult.objects.create(results='first results') results = UserStatResult.objects.create(results='first results')
userstat = UserStat.objects.create(user=user, posts=150, userstat = UserStat.objects.create(user=user, posts=150,
results=results) results=results)
details = StatDetails.objects.create(base_stats=userstat, comments=259) StatDetails.objects.create(base_stats=userstat, comments=259)
user2 = User.objects.create(username="bob") user2 = User.objects.create(username="bob")
results2 = UserStatResult.objects.create(results='moar results') results2 = UserStatResult.objects.create(results='moar results')

View File

@ -61,7 +61,7 @@ class SelectRelatedRegressTests(TestCase):
s = Student.objects.create(person = usp) s = Student.objects.create(person = usp)
o = Organizer.objects.create(person = uop) o = Organizer.objects.create(person = uop)
c = Class.objects.create(org=o) c = Class.objects.create(org=o)
e = Enrollment.objects.create(std=s, cls=c) Enrollment.objects.create(std=s, cls=c)
e_related = Enrollment.objects.all().select_related()[0] e_related = Enrollment.objects.all().select_related()[0]
self.assertEqual(e_related.std.person.user.name, "std") self.assertEqual(e_related.std.person.user.name, "std")
@ -77,7 +77,7 @@ class SelectRelatedRegressTests(TestCase):
for country before getting status. for country before getting status.
""" """
australia = Country.objects.create(name='Australia') Country.objects.create(name='Australia')
active = ClientStatus.objects.create(name='active') active = ClientStatus.objects.create(name='active')
client = Client.objects.create(name='client', status=active) client = Client.objects.create(name='client', status=active)
@ -92,8 +92,8 @@ class SelectRelatedRegressTests(TestCase):
def test_multi_table_inheritance(self): def test_multi_table_inheritance(self):
""" Exercising select_related() with multi-table model inheritance. """ """ Exercising select_related() with multi-table model inheritance. """
c1 = Child.objects.create(name="child1", value=42) c1 = Child.objects.create(name="child1", value=42)
i1 = Item.objects.create(name="item1", child=c1) Item.objects.create(name="item1", child=c1)
i2 = Item.objects.create(name="item2") Item.objects.create(name="item2")
self.assertQuerysetEqual( self.assertQuerysetEqual(
Item.objects.select_related("child").order_by("name"), Item.objects.select_related("child").order_by("name"),
@ -111,14 +111,14 @@ class SelectRelatedRegressTests(TestCase):
active = ClientStatus.objects.create(name='active') active = ClientStatus.objects.create(name='active')
wa = State.objects.create(name="Western Australia", country=australia) wa = State.objects.create(name="Western Australia", country=australia)
c1 = Client.objects.create(name='Brian Burke', state=wa, status=active) Client.objects.create(name='Brian Burke', state=wa, status=active)
burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke') burke = Client.objects.select_related('state').defer('state__name').get(name='Brian Burke')
self.assertEqual(burke.name, 'Brian Burke') self.assertEqual(burke.name, 'Brian Burke')
self.assertEqual(burke.state.name, 'Western Australia') self.assertEqual(burke.state.name, 'Western Australia')
# Still works if we're dealing with an inherited class # Still works if we're dealing with an inherited class
sc1 = SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42) SpecialClient.objects.create(name='Troy Buswell', state=wa, status=active, value=42)
troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell') troy = SpecialClient.objects.select_related('state').defer('state__name').get(name='Troy Buswell')
self.assertEqual(troy.name, 'Troy Buswell') self.assertEqual(troy.name, 'Troy Buswell')
@ -168,7 +168,7 @@ class SelectRelatedRegressTests(TestCase):
""" """
hen = Hen.objects.create(name='Hen') hen = Hen.objects.create(name='Hen')
chick = Chick.objects.create(name='Chick', mother=hen) Chick.objects.create(name='Chick', mother=hen)
self.assertEqual(Chick.objects.all()[0].mother.name, 'Hen') self.assertEqual(Chick.objects.all()[0].mother.name, 'Hen')
self.assertEqual(Chick.objects.select_related()[0].mother.name, 'Hen') self.assertEqual(Chick.objects.select_related()[0].mother.name, 'Hen')

View File

@ -198,7 +198,7 @@ class SerializersTestBase(object):
mv.save() mv.save()
with self.assertNumQueries(0): with self.assertNumQueries(0):
serial_str = serializers.serialize(self.serializer_name, [mv]) serializers.serialize(self.serializer_name, [mv])
def test_serialize_with_null_pk(self): def test_serialize_with_null_pk(self):
""" """

View File

@ -144,8 +144,8 @@ def m2m_compare(testcase, pk, klass, data):
testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')]) testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')])
def im2m_compare(testcase, pk, klass, data): def im2m_compare(testcase, pk, klass, data):
instance = klass.objects.get(id=pk) klass.objects.get(id=pk)
#actually nothing else to check, the instance just should exist # actually nothing else to check, the instance just should exist
def im_compare(testcase, pk, klass, data): def im_compare(testcase, pk, klass, data):
instance = klass.objects.get(id=pk) instance = klass.objects.get(id=pk)
@ -478,7 +478,7 @@ def naturalKeySerializerTest(format, self):
instance_count[klass] = klass.objects.count() instance_count[klass] = klass.objects.count()
# use_natural_keys is deprecated and to be removed in Django 1.9 # use_natural_keys is deprecated and to be removed in Django 1.9
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
# Serialize the test database # Serialize the test database
serialized_data = serializers.serialize(format, objects, indent=2, serialized_data = serializers.serialize(format, objects, indent=2,

View File

@ -172,7 +172,7 @@ class SignalTests(TestCase):
a, b = MyReceiver(1), MyReceiver(2) a, b = MyReceiver(1), MyReceiver(2)
signals.post_save.connect(sender=Person, receiver=a) signals.post_save.connect(sender=Person, receiver=a)
signals.post_save.connect(sender=Person, receiver=b) signals.post_save.connect(sender=Person, receiver=b)
p = Person.objects.create(first_name='John', last_name='Smith') Person.objects.create(first_name='John', last_name='Smith')
self.assertTrue(a._run) self.assertTrue(a._run)
self.assertTrue(b._run) self.assertTrue(b._run)

View File

@ -28,9 +28,9 @@ class SitesFrameworkTestCase(TestCase):
self.assertEqual(CustomArticle.on_site.all().get(), article) self.assertEqual(CustomArticle.on_site.all().get(), article)
def test_invalid_name(self): def test_invalid_name(self):
article = InvalidArticle.objects.create(title="Bad News!", site_id=settings.SITE_ID) InvalidArticle.objects.create(title="Bad News!", site_id=settings.SITE_ID)
self.assertRaises(ValueError, InvalidArticle.on_site.all) self.assertRaises(ValueError, InvalidArticle.on_site.all)
def test_invalid_field_type(self): def test_invalid_field_type(self):
article = ConfusedArticle.objects.create(title="More Bad News!", site=settings.SITE_ID) ConfusedArticle.objects.create(title="More Bad News!", site=settings.SITE_ID)
self.assertRaises(TypeError, ConfusedArticle.on_site.all) self.assertRaises(TypeError, ConfusedArticle.on_site.all)

View File

@ -561,7 +561,7 @@ class TestCollectionCachedStorage(BaseCollectionTestCase,
""" """
finders._finders.clear() finders._finders.clear()
err = six.StringIO() err = six.StringIO()
with self.assertRaises(Exception) as cm: with self.assertRaises(Exception):
call_command('collectstatic', interactive=False, verbosity=0, stderr=err) call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue()) self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())

View File

@ -187,7 +187,7 @@ class SimpleTemplateResponseTest(TestCase):
response.render() response.render()
pickled_response = pickle.dumps(response) pickled_response = pickle.dumps(response)
unpickled_response = pickle.loads(pickled_response) unpickled_response = pickle.loads(pickled_response)
repickled_response = pickle.dumps(unpickled_response) pickle.dumps(unpickled_response)
def test_pickling_cookie(self): def test_pickling_cookie(self):
response = SimpleTemplateResponse('first/test.html', { response = SimpleTemplateResponse('first/test.html', {
@ -293,7 +293,7 @@ class TemplateResponseTest(TestCase):
response.render() response.render()
pickled_response = pickle.dumps(response) pickled_response = pickle.dumps(response)
unpickled_response = pickle.loads(pickled_response) unpickled_response = pickle.loads(pickled_response)
repickled_response = pickle.dumps(unpickled_response) pickle.dumps(unpickled_response)
class CustomURLConfTest(TestCase): class CustomURLConfTest(TestCase):

View File

@ -20,10 +20,10 @@ class UnicodeTests(TestCase):
self.assertRaises(TemplateEncodingError, Template, s) self.assertRaises(TemplateEncodingError, Template, s)
# Contexts can be constructed from unicode or UTF-8 bytestrings. # Contexts can be constructed from unicode or UTF-8 bytestrings.
c1 = Context({b"var": b"foo"}) Context({b"var": b"foo"})
c2 = Context({"var": b"foo"}) Context({"var": b"foo"})
c3 = Context({b"var": "Đđ"}) c3 = Context({b"var": "Đđ"})
c4 = Context({"var": b"\xc4\x90\xc4\x91"}) Context({"var": b"\xc4\x90\xc4\x91"})
# Since both templates and all four contexts represent the same thing, # Since both templates and all four contexts represent the same thing,
# they all render the same (and are returned as unicode objects and # they all render the same (and are returned as unicode objects and

View File

@ -370,7 +370,6 @@ class TemplateLoaderTests(TestCase):
template that does not exist does not raise an exception at parse template that does not exist does not raise an exception at parse
time. time.
""" """
ctx = Context()
tmpl = Template('{% include "this_does_not_exist.html" %}') tmpl = Template('{% include "this_does_not_exist.html" %}')
self.assertIsInstance(tmpl, Template) self.assertIsInstance(tmpl, Template)
@ -440,7 +439,7 @@ class TemplateRegressionTests(TestCase):
# Regression test for #19392 # Regression test for #19392
with six.assertRaisesRegex(self, template.TemplateSyntaxError, with six.assertRaisesRegex(self, template.TemplateSyntaxError,
"The syntax of 'url' changed in Django 1.5, see the docs."): "The syntax of 'url' changed in Django 1.5, see the docs."):
t = Template('{% url my-view %}') # not a variable = old syntax Template('{% url my-view %}') # not a variable = old syntax
@override_settings(DEBUG=True, TEMPLATE_DEBUG=True) @override_settings(DEBUG=True, TEMPLATE_DEBUG=True)
def test_no_wrapped_exception(self): def test_no_wrapped_exception(self):
@ -458,7 +457,7 @@ class TemplateRegressionTests(TestCase):
def test_invalid_block_suggestion(self): def test_invalid_block_suggestion(self):
# See #7876 # See #7876
try: try:
t = Template("{% if 1 %}lala{% endblock %}{% endif %}") Template("{% if 1 %}lala{% endblock %}{% endif %}")
except TemplateSyntaxError as e: except TemplateSyntaxError as e:
self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'") self.assertEqual(e.args[0], "Invalid block tag: 'endblock', expected 'elif', 'else' or 'endif'")
@ -1863,7 +1862,7 @@ class TemplateTagLoading(unittest.TestCase):
egg_name = '%s/tagsegg.egg' % self.egg_dir egg_name = '%s/tagsegg.egg' % self.egg_dir
sys.path.append(egg_name) sys.path.append(egg_name)
settings.INSTALLED_APPS = ('tagsegg',) settings.INSTALLED_APPS = ('tagsegg',)
t = template.Template(ttext) template.Template(ttext)
class RequestContextTests(unittest.TestCase): class RequestContextTests(unittest.TestCase):

View File

@ -419,7 +419,7 @@ class ClientTest(TestCase):
pass pass
from django.contrib.sessions.models import Session from django.contrib.sessions.models import Session
response = self.client.post('/test_client/session_view/') self.client.post('/test_client/session_view/')
# Check that the session was modified # Check that the session was modified
self.assertEqual(self.client.session['tobacconist'], 'hovercraft') self.assertEqual(self.client.session['tobacconist'], 'hovercraft')

View File

@ -810,7 +810,7 @@ class ExceptionTests(TestCase):
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:
response = self.client.get("/test_client_regress/staff_only/") self.client.get("/test_client_regress/staff_only/")
self.fail("General users should not be able to visit this page") self.fail("General users should not be able to visit this page")
except CustomTestException: except CustomTestException:
pass pass
@ -840,7 +840,7 @@ class TemplateExceptionTests(TestCase):
def test_bad_404_template(self): def test_bad_404_template(self):
"Errors found when rendering 404 error templates are re-raised" "Errors found when rendering 404 error templates are re-raised"
try: try:
response = self.client.get("/no_such_view/") self.client.get("/no_such_view/")
self.fail("Should get error about syntax error in template") self.fail("Should get error about syntax error in template")
except TemplateSyntaxError: except TemplateSyntaxError:
pass pass

View File

@ -35,7 +35,7 @@ def request_data(request, template='base.html', data='sausage'):
"A simple view that returns the request data in the context" "A simple view that returns the request data in the context"
# request.REQUEST is deprecated, but needs testing until removed. # request.REQUEST is deprecated, but needs testing until removed.
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True):
warnings.simplefilter("always") warnings.simplefilter("always")
request_foo = request.REQUEST.get('foo') request_foo = request.REQUEST.get('foo')
request_bar = request.REQUEST.get('bar') request_bar = request.REQUEST.get('bar')

View File

@ -257,7 +257,7 @@ class LegacyDatabaseTests(TestCase):
def test_filter_date_field_with_aware_datetime(self): def test_filter_date_field_with_aware_datetime(self):
# Regression test for #17742 # Regression test for #17742
day = datetime.date(2011, 9, 1) day = datetime.date(2011, 9, 1)
event = AllDayEvent.objects.create(day=day) AllDayEvent.objects.create(day=day)
# This is 2011-09-02T01:30:00+03:00 in EAT # This is 2011-09-02T01:30:00+03:00 in EAT
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists()) self.assertTrue(AllDayEvent.objects.filter(day__gte=dt).exists())
@ -537,7 +537,7 @@ class NewDatabaseTests(TestCase):
def test_filter_date_field_with_aware_datetime(self): def test_filter_date_field_with_aware_datetime(self):
# Regression test for #17742 # Regression test for #17742
day = datetime.date(2011, 9, 1) day = datetime.date(2011, 9, 1)
event = AllDayEvent.objects.create(day=day) AllDayEvent.objects.create(day=day)
# This is 2011-09-02T01:30:00+03:00 in EAT # This is 2011-09-02T01:30:00+03:00 in EAT
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC) dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists()) self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists())

View File

@ -228,7 +228,7 @@ class ResolverTests(unittest.TestCase):
proxy_url = reverse_lazy('named-url1', urlconf=urls) proxy_url = reverse_lazy('named-url1', urlconf=urls)
resolver = get_resolver(urls) resolver = get_resolver(urls)
try: try:
match = resolver.resolve(proxy_url) resolver.resolve(proxy_url)
except TypeError: except TypeError:
self.fail('Failed to coerce lazy object to text') self.fail('Failed to coerce lazy object to text')
@ -290,7 +290,7 @@ class ReverseLazyTest(TestCase):
self.assertRedirects(response, "/redirected_to/", status_code=301) self.assertRedirects(response, "/redirected_to/", status_code=301)
def test_user_permission_with_lazy_reverse(self): def test_user_permission_with_lazy_reverse(self):
user = User.objects.create_user('alfred', 'alfred@example.com', password='testpw') User.objects.create_user('alfred', 'alfred@example.com', password='testpw')
response = self.client.get('/login_required_view/') response = self.client.get('/login_required_view/')
self.assertRedirects(response, "/login/?next=/login_required_view/", status_code=302) self.assertRedirects(response, "/login/?next=/login_required_view/", status_code=302)
self.client.login(username='alfred', password='testpw') self.client.login(username='alfred', password='testpw')

View File

@ -148,8 +148,6 @@ class MergeDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
d3 = {'chris3':'cool3', 'camri3':'cute3', 'cotton3':'adorable3', d3 = {'chris3':'cool3', 'camri3':'cute3', 'cotton3':'adorable3',
'tulip3':'snuggable3'} 'tulip3':'snuggable3'}
d4 = {'twoofme': 'secondone'}
md = MergeDict(d1, d2, d3) md = MergeDict(d1, d2, d3)
self.assertEqual(md['chris'], 'cool') self.assertEqual(md['chris'], 'cool')

View File

@ -73,7 +73,7 @@ class DecoratorFromMiddlewareTests(TestCase):
return HttpResponse(t.render(Context({}))) return HttpResponse(t.render(Context({})))
request = self.rf.get('/') request = self.rf.get('/')
response = normal_view(request) normal_view(request)
self.assertTrue(getattr(request, 'process_request_reached', False)) self.assertTrue(getattr(request, 'process_request_reached', False))
self.assertTrue(getattr(request, 'process_view_reached', False)) self.assertTrue(getattr(request, 'process_view_reached', False))
# process_template_response must not be called for HttpResponse # process_template_response must not be called for HttpResponse

View File

@ -69,7 +69,7 @@ class TestUtilsSimpleLazyObject(TestCase):
self.assertEqual(empty, x._wrapped) self.assertEqual(empty, x._wrapped)
# Second, for an evaluated SimpleLazyObject # Second, for an evaluated SimpleLazyObject
name = x.name # evaluate x.name # evaluate
self.assertIsInstance(x._wrapped, _ComplexObject) self.assertIsInstance(x._wrapped, _ComplexObject)
# __repr__ contains __repr__ of wrapped object # __repr__ contains __repr__ of wrapped object
self.assertEqual("<SimpleLazyObject: %r>" % x._wrapped, repr(x)) self.assertEqual("<SimpleLazyObject: %r>" % x._wrapped, repr(x))
@ -99,7 +99,7 @@ class TestUtilsSimpleLazyObject(TestCase):
self.assertEqual(s2, complex_object()) self.assertEqual(s2, complex_object())
# Second, for an evaluated SimpleLazyObject # Second, for an evaluated SimpleLazyObject
name = s.name # evaluate s.name # evaluate
self.assertIsNot(s._wrapped, empty) self.assertIsNot(s._wrapped, empty)
s3 = copy.deepcopy(s) s3 = copy.deepcopy(s)
self.assertEqual(s3, complex_object()) self.assertEqual(s3, complex_object())
@ -186,15 +186,15 @@ class TestUtilsSimpleLazyObjectDjangoTestCase(DjangoTestCase):
# This would fail with "TypeError: can't pickle instancemethod objects", # This would fail with "TypeError: can't pickle instancemethod objects",
# only on Python 2.X. # only on Python 2.X.
pickled = pickle.dumps(x) pickle.dumps(x)
# Try the variant protocol levels. # Try the variant protocol levels.
pickled = pickle.dumps(x, 0) pickle.dumps(x, 0)
pickled = pickle.dumps(x, 1) pickle.dumps(x, 1)
pickled = pickle.dumps(x, 2) pickle.dumps(x, 2)
if six.PY2: if six.PY2:
import cPickle import cPickle
# This would fail with "TypeError: expected string or Unicode object, NoneType found". # This would fail with "TypeError: expected string or Unicode object, NoneType found".
pickled = cPickle.dumps(x) cPickle.dumps(x)

View File

@ -77,7 +77,7 @@ class PerformUniqueChecksTest(TestCase):
mtv.full_clean() mtv.full_clean()
def test_unique_for_date(self): def test_unique_for_date(self):
p1 = Post.objects.create(title="Django 1.0 is released", Post.objects.create(title="Django 1.0 is released",
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3)) p = Post(title="Django 1.0 is released", posted=datetime.date(2008, 9, 3))
@ -109,7 +109,7 @@ class PerformUniqueChecksTest(TestCase):
self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']}) self.assertEqual(cm.exception.message_dict, {'posted': ['This field cannot be null.']})
def test_unique_for_date_with_nullable_date(self): def test_unique_for_date_with_nullable_date(self):
p1 = FlexibleDatePost.objects.create(title="Django 1.0 is released", FlexibleDatePost.objects.create(title="Django 1.0 is released",
slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3)) slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
p = FlexibleDatePost(title="Django 1.0 is released") p = FlexibleDatePost(title="Django 1.0 is released")
@ -131,7 +131,7 @@ class PerformUniqueChecksTest(TestCase):
self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.") self.fail("unique_for_month checks shouldn't trigger when the associated DateField is None.")
def test_unique_errors(self): def test_unique_errors(self):
m1 = UniqueErrorsModel.objects.create(name='Some Name', no=10) UniqueErrorsModel.objects.create(name='Some Name', no=10)
m = UniqueErrorsModel(name='Some Name', no=11) m = UniqueErrorsModel(name='Some Name', no=11)
with self.assertRaises(ValidationError) as cm: with self.assertRaises(ValidationError) as cm:
m.full_clean() m.full_clean()

View File

@ -171,8 +171,8 @@ def non_sensitive_view(request):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
try: try:
raise Exception raise Exception
except Exception: except Exception:
@ -186,8 +186,8 @@ def sensitive_view(request):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
try: try:
raise Exception raise Exception
except Exception: except Exception:
@ -201,8 +201,8 @@ def paranoid_view(request):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
try: try:
raise Exception raise Exception
except Exception: except Exception:
@ -223,7 +223,7 @@ def sensitive_args_function(sauce):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
raise Exception raise Exception
def sensitive_kwargs_function_caller(request): def sensitive_kwargs_function_caller(request):
@ -239,7 +239,7 @@ def sensitive_kwargs_function(sauce=None):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
raise Exception raise Exception
class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter): class UnsafeExceptionReporterFilter(SafeExceptionReporterFilter):
@ -260,8 +260,8 @@ def custom_exception_reporter_filter_view(request):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's source # so that the tests don't return false positives when the function's source
# is displayed in the exception report. # is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
request.exception_reporter_filter = UnsafeExceptionReporterFilter() request.exception_reporter_filter = UnsafeExceptionReporterFilter()
try: try:
raise Exception raise Exception
@ -278,8 +278,8 @@ class Klass(object):
# Do not just use plain strings for the variables' values in the code # Do not just use plain strings for the variables' values in the code
# so that the tests don't return false positives when the function's # so that the tests don't return false positives when the function's
# source is displayed in the exception report. # source is displayed in the exception report.
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
try: try:
raise Exception raise Exception
except Exception: except Exception:
@ -294,8 +294,8 @@ def sensitive_method_view(request):
@sensitive_variables('sauce') @sensitive_variables('sauce')
@sensitive_post_parameters('bacon-key', 'sausage-key') @sensitive_post_parameters('bacon-key', 'sausage-key')
def multivalue_dict_key_error(request): def multivalue_dict_key_error(request):
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd']) # NOQA
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']) # NOQA
try: try:
request.POST['bar'] request.POST['bar']
except Exception: except Exception: