mirror of https://github.com/django/django.git
Removed unused local variables in tests.
This commit is contained in:
parent
5f52590368
commit
96d1d4e292
|
@ -4,7 +4,7 @@ install-script = scripts/rpm-install.sh
|
|||
|
||||
[flake8]
|
||||
exclude=./django/utils/dictconfig.py,./django/contrib/comments/*,./django/utils/unittest.py,./tests/comment_tests/*,./django/test/_doctest.py
|
||||
ignore=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]
|
||||
license-file = LICENSE
|
||||
|
|
|
@ -168,7 +168,7 @@ class DeprecatingRequestMergeDictTest(SimpleTestCase):
|
|||
with warnings.catch_warnings(record=True) as recorded:
|
||||
warnings.simplefilter('always')
|
||||
request = RequestFactory().get('/')
|
||||
_ = request.REQUEST
|
||||
request.REQUEST # evaluate
|
||||
|
||||
msgs = [str(warning.message) for warning in recorded]
|
||||
self.assertEqual(msgs, [
|
||||
|
|
|
@ -351,7 +351,7 @@ class FTimeDeltaTests(TestCase):
|
|||
def test_delta_invalid_op_mult(self):
|
||||
raised = False
|
||||
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:
|
||||
raised = True
|
||||
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):
|
||||
raised = False
|
||||
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:
|
||||
raised = True
|
||||
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):
|
||||
raised = False
|
||||
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:
|
||||
raised = True
|
||||
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):
|
||||
raised = False
|
||||
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:
|
||||
raised = True
|
||||
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):
|
||||
raised = False
|
||||
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:
|
||||
raised = True
|
||||
self.assertTrue(raised, "TypeError not raised on attempt to binary or a datetime with a timedelta.")
|
||||
|
|
|
@ -160,7 +160,7 @@ class ExtraRegressTests(TestCase):
|
|||
columns, we can (and should) ignore those columns. They don't change
|
||||
the result and cause incorrect SQL to be produced otherwise.
|
||||
"""
|
||||
rm = RevisionableModel.objects.create(
|
||||
RevisionableModel.objects.create(
|
||||
title='First Revision',
|
||||
when=datetime.datetime(2008, 9, 28, 10, 30, 0)
|
||||
)
|
||||
|
|
|
@ -174,7 +174,7 @@ class FieldDeconstructionTests(TestCase):
|
|||
self.assertEqual(kwargs, {})
|
||||
|
||||
def test_ip_address_field(self):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always")
|
||||
field = models.IPAddressField()
|
||||
name, path, args, kwargs = field.deconstruct()
|
||||
|
|
|
@ -241,8 +241,8 @@ class FileStorageTests(unittest.TestCase):
|
|||
self.assertFalse(self.storage.exists('storage_test_2'))
|
||||
self.assertFalse(self.storage.exists('storage_dir_1'))
|
||||
|
||||
f = self.storage.save('storage_test_1', ContentFile('custom content'))
|
||||
f = self.storage.save('storage_test_2', ContentFile('custom content'))
|
||||
self.storage.save('storage_test_1', ContentFile('custom content'))
|
||||
self.storage.save('storage_test_2', ContentFile('custom content'))
|
||||
os.mkdir(os.path.join(self.temp_dir, 'storage_dir_1'))
|
||||
|
||||
dirs, files = self.storage.listdir('')
|
||||
|
@ -428,7 +428,7 @@ class FileSaveRaceConditionTest(unittest.TestCase):
|
|||
|
||||
def test_race_condition(self):
|
||||
self.thread.start()
|
||||
name = self.save_file('conflict')
|
||||
self.save_file('conflict')
|
||||
self.thread.join()
|
||||
self.assertTrue(self.storage.exists('conflict'))
|
||||
self.assertTrue(self.storage.exists('conflict_1'))
|
||||
|
|
|
@ -335,7 +335,7 @@ class FileUploadTests(TestCase):
|
|||
"""A handler that'll access POST during an exception."""
|
||||
def handle_uncaught_exception(self, request, resolver, exc_info):
|
||||
ret = super(POSTAccessingHandler, self).handle_uncaught_exception(request, resolver, exc_info)
|
||||
p = request.POST
|
||||
request.POST # evaluate
|
||||
return ret
|
||||
|
||||
# Maybe this is a little more complicated that it needs to be; but if
|
||||
|
@ -356,7 +356,7 @@ class FileUploadTests(TestCase):
|
|||
'file_field': fp,
|
||||
}
|
||||
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:
|
||||
self.assertFalse(
|
||||
str(err) == str(reference_error),
|
||||
|
@ -444,7 +444,7 @@ class MultiParserTests(unittest.TestCase):
|
|||
def test_empty_upload_handlers(self):
|
||||
# We're not actually parsing here; just checking if the parser properly
|
||||
# instantiates with empty upload handlers.
|
||||
parser = MultiPartParser({
|
||||
MultiPartParser({
|
||||
'CONTENT_TYPE': 'multipart/form-data; boundary=_foo',
|
||||
'CONTENT_LENGTH': '1'
|
||||
}, StringIO('x'), [], 'utf-8')
|
||||
|
|
|
@ -170,7 +170,7 @@ class FileTests(unittest.TestCase):
|
|||
# See #14681, stdlib gzip module crashes if mode is set to None
|
||||
file = SimpleUploadedFile("mode_test.txt", b"content")
|
||||
self.assertFalse(hasattr(file, 'mode'))
|
||||
g = gzip.GzipFile(fileobj=file)
|
||||
gzip.GzipFile(fileobj=file)
|
||||
|
||||
|
||||
class FileMoveSafeTests(unittest.TestCase):
|
||||
|
|
|
@ -194,7 +194,7 @@ class FormsErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
|
|||
'required': 'REQUIRED',
|
||||
'invalid': 'INVALID IP ADDRESS',
|
||||
}
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always")
|
||||
f = IPAddressField(error_messages=e)
|
||||
self.assertFormErrors(['REQUIRED'], f.clean, '')
|
||||
|
@ -243,9 +243,9 @@ class ModelChoiceFieldErrorMessagesTestCase(TestCase, AssertFormErrorsMixin):
|
|||
def test_modelchoicefield(self):
|
||||
# Create choices for the model choice field tests below.
|
||||
from forms_tests.models import ChoiceModel
|
||||
c1 = ChoiceModel.objects.create(pk=1, name='a')
|
||||
c2 = ChoiceModel.objects.create(pk=2, name='b')
|
||||
c3 = ChoiceModel.objects.create(pk=3, name='c')
|
||||
ChoiceModel.objects.create(pk=1, name='a')
|
||||
ChoiceModel.objects.create(pk=2, name='b')
|
||||
ChoiceModel.objects.create(pk=3, name='c')
|
||||
|
||||
# ModelChoiceField
|
||||
e = {
|
||||
|
|
|
@ -535,7 +535,7 @@ class FormsExtraTestCase(TestCase, AssertFormErrorsMixin):
|
|||
self.assertEqual(f.cleaned_data['field1'], 'some text,JP,2007-04-25 06:24:00')
|
||||
|
||||
def test_ipaddress(self):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always")
|
||||
f = IPAddressField()
|
||||
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, '256.125.1.5')
|
||||
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always")
|
||||
f = IPAddressField(required=False)
|
||||
self.assertEqual(f.clean(''), '')
|
||||
|
|
|
@ -336,20 +336,6 @@ class FormsFormsetTestCase(TestCase):
|
|||
def test_more_initial_data(self):
|
||||
# The extra argument also works when the formset is pre-filled with initial
|
||||
# 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}]
|
||||
ChoiceFormSet = formset_factory(Choice, extra=3)
|
||||
formset = ChoiceFormSet(initial=initial, auto_id=False, prefix='choices')
|
||||
|
|
|
@ -94,9 +94,9 @@ class ModelFormCallableModelDefault(TestCase):
|
|||
|
||||
def test_callable_initial_value(self):
|
||||
"The initial value for a callable default returning a queryset is the pk (refs #13769)"
|
||||
obj1 = ChoiceOptionModel.objects.create(id=1, name='default')
|
||||
obj2 = ChoiceOptionModel.objects.create(id=2, name='option 2')
|
||||
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
|
||||
ChoiceOptionModel.objects.create(id=1, name='default')
|
||||
ChoiceOptionModel.objects.create(id=2, name='option 2')
|
||||
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">
|
||||
<option value="1" selected="selected">ChoiceOption 1</option>
|
||||
<option value="2">ChoiceOption 2</option>
|
||||
|
@ -120,7 +120,7 @@ class ModelFormCallableModelDefault(TestCase):
|
|||
|
||||
def test_initial_instance_value(self):
|
||||
"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')
|
||||
obj3 = ChoiceOptionModel.objects.create(id=3, name='option 3')
|
||||
self.assertHTMLEqual(ChoiceFieldForm(initial={
|
||||
|
|
|
@ -178,7 +178,6 @@ class GenericInlineAdminParametersTest(TestCase):
|
|||
With extra=5 and max_num=2, there should be only 2 forms.
|
||||
"""
|
||||
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)
|
||||
formset = response.context['inline_admin_formsets'][0].formset
|
||||
self.assertEqual(formset.total_form_count(), 2)
|
||||
|
@ -422,13 +421,13 @@ class GenericInlineModelAdminTest(TestCase):
|
|||
|
||||
def get_formsets(self, request, obj=None):
|
||||
# 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")
|
||||
return super(EpisodeAdmin, self).get_formsets(request, obj)
|
||||
|
||||
ma = EpisodeAdmin(Episode, self.site)
|
||||
inlines = ma.get_inline_instances(request)
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always")
|
||||
for (formset, inline), other_inline in zip(ma.get_formsets_with_inlines(request), inlines):
|
||||
self.assertIsInstance(formset, other_inline.get_formset(request).__class__)
|
||||
|
|
|
@ -19,7 +19,7 @@ class GenericRelationsTests(TestCase):
|
|||
platypus = Animal.objects.create(
|
||||
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)
|
||||
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
|
||||
# defined. That's OK, because you can create TaggedItems explicitly.
|
||||
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
|
||||
# bit more explicit.
|
||||
|
|
|
@ -76,7 +76,7 @@ class ViewTest(unittest.TestCase):
|
|||
Test that a view can't be accidentally instantiated before deployment
|
||||
"""
|
||||
try:
|
||||
view = SimpleView(key='value').as_view()
|
||||
SimpleView(key='value').as_view()
|
||||
self.fail('Should not be able to instantiate a view')
|
||||
except AttributeError:
|
||||
pass
|
||||
|
@ -86,7 +86,7 @@ class ViewTest(unittest.TestCase):
|
|||
Test that a view can't be accidentally instantiated before deployment
|
||||
"""
|
||||
try:
|
||||
view = SimpleView.as_view('value')
|
||||
SimpleView.as_view('value')
|
||||
self.fail('Should not be able to use non-keyword arguments instantiating a view')
|
||||
except TypeError:
|
||||
pass
|
||||
|
|
|
@ -12,7 +12,7 @@ from .models import Book, BookSigning
|
|||
|
||||
def _make_books(n, base_date):
|
||||
for i in range(n):
|
||||
b = Book.objects.create(
|
||||
Book.objects.create(
|
||||
name='Book %d' % i,
|
||||
slug='book-%d' % i,
|
||||
pages=100+i,
|
||||
|
@ -158,7 +158,7 @@ class YearArchiveViewTests(TestCase):
|
|||
def test_year_view_allow_future(self):
|
||||
# Create a new book in the future
|
||||
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)
|
||||
self.assertEqual(res.status_code, 404)
|
||||
|
||||
|
|
|
@ -122,15 +122,15 @@ class CreateViewTests(TestCase):
|
|||
|
||||
def test_create_without_redirect(self):
|
||||
try:
|
||||
res = self.client.post('/edit/authors/create/naive/',
|
||||
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
|
||||
self.client.post('/edit/authors/create/naive/',
|
||||
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
|
||||
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
|
||||
except ImproperlyConfigured:
|
||||
pass
|
||||
|
||||
def test_create_restricted(self):
|
||||
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.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)>'])
|
||||
|
||||
def test_update_without_redirect(self):
|
||||
try:
|
||||
a = Author.objects.create(
|
||||
name='Randall Munroe',
|
||||
slug='randall-munroe',
|
||||
)
|
||||
res = self.client.post('/edit/author/%d/update/naive/' % a.pk,
|
||||
a = Author.objects.create(
|
||||
name='Randall Munroe',
|
||||
slug='randall-munroe',
|
||||
)
|
||||
# Should raise exception -- No redirect URL provided, and no
|
||||
# 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'})
|
||||
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
|
||||
except ImproperlyConfigured:
|
||||
pass
|
||||
|
||||
def test_update_get_object(self):
|
||||
a = Author.objects.create(
|
||||
|
@ -365,12 +364,11 @@ class DeleteViewTests(TestCase):
|
|||
self.assertQuerysetEqual(Author.objects.all(), [])
|
||||
|
||||
def test_delete_without_redirect(self):
|
||||
try:
|
||||
a = Author.objects.create(
|
||||
name='Randall Munroe',
|
||||
slug='randall-munroe',
|
||||
)
|
||||
res = self.client.post('/edit/author/%d/delete/naive/' % a.pk)
|
||||
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
|
||||
except ImproperlyConfigured:
|
||||
pass
|
||||
a = Author.objects.create(
|
||||
name='Randall Munroe',
|
||||
slug='randall-munroe',
|
||||
)
|
||||
# Should raise exception -- No redirect URL provided, and no
|
||||
# get_absolute_url provided
|
||||
with self.assertRaises(ImproperlyConfigured):
|
||||
self.client.post('/edit/author/%d/delete/naive/' % a.pk)
|
||||
|
|
|
@ -27,11 +27,11 @@ class EarliestOrLatestTests(TestCase):
|
|||
headline="Article 2", pub_date=datetime(2005, 7, 27),
|
||||
expire_date=datetime(2005, 7, 28)
|
||||
)
|
||||
a3 = Article.objects.create(
|
||||
Article.objects.create(
|
||||
headline="Article 3", pub_date=datetime(2005, 7, 28),
|
||||
expire_date=datetime(2005, 8, 27)
|
||||
)
|
||||
a4 = Article.objects.create(
|
||||
Article.objects.create(
|
||||
headline="Article 4", pub_date=datetime(2005, 7, 28),
|
||||
expire_date=datetime(2005, 7, 30)
|
||||
)
|
||||
|
@ -72,7 +72,7 @@ class EarliestOrLatestTests(TestCase):
|
|||
headline="Article 1", pub_date=datetime(2005, 7, 26),
|
||||
expire_date=datetime(2005, 9, 1)
|
||||
)
|
||||
a2 = Article.objects.create(
|
||||
Article.objects.create(
|
||||
headline="Article 2", pub_date=datetime(2005, 7, 27),
|
||||
expire_date=datetime(2005, 7, 28)
|
||||
)
|
||||
|
@ -117,7 +117,7 @@ class EarliestOrLatestTests(TestCase):
|
|||
def test_latest_manual(self):
|
||||
# You can still use latest() with a model that doesn't have
|
||||
# "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))
|
||||
self.assertRaises(AssertionError, Person.objects.latest)
|
||||
self.assertEqual(Person.objects.latest("birthday"), p2)
|
||||
|
|
|
@ -51,7 +51,7 @@ class GetOrCreateTests(TestCase):
|
|||
|
||||
# If you specify an existing primary key, but different other fields,
|
||||
# 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,
|
||||
ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
|
||||
)
|
||||
|
@ -63,7 +63,7 @@ class GetOrCreateTests(TestCase):
|
|||
# the actual traceback. Refs #16340.
|
||||
try:
|
||||
ManualPrimaryKeyTest.objects.get_or_create(id=1, data="Different")
|
||||
except IntegrityError as e:
|
||||
except IntegrityError:
|
||||
formatted_traceback = traceback.format_exc()
|
||||
self.assertIn(str('obj.save'), formatted_traceback)
|
||||
|
||||
|
@ -193,6 +193,6 @@ class UpdateOrCreateTests(TestCase):
|
|||
# the actual traceback. Refs #16340.
|
||||
try:
|
||||
ManualPrimaryKeyTest.objects.update_or_create(id=1, data="Different")
|
||||
except IntegrityError as e:
|
||||
except IntegrityError:
|
||||
formatted_traceback = traceback.format_exc()
|
||||
self.assertIn('obj.save', formatted_traceback)
|
||||
|
|
|
@ -1198,16 +1198,16 @@ class LocaleMiddlewareTests(TransRealMixin, TestCase):
|
|||
|
||||
# Clear the session data before request
|
||||
session.save()
|
||||
response = self.client.get('/en/simple/')
|
||||
self.client.get('/en/simple/')
|
||||
self.assertEqual(self.client.session['django_language'], 'en')
|
||||
|
||||
# Clear the session data before request
|
||||
session.save()
|
||||
response = self.client.get('/fr/simple/')
|
||||
self.client.get('/fr/simple/')
|
||||
self.assertEqual(self.client.session['django_language'], 'fr')
|
||||
|
||||
# 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')
|
||||
|
||||
|
||||
|
|
|
@ -362,12 +362,12 @@ class SecurityLoggerTest(TestCase):
|
|||
|
||||
def test_suspicious_operation_creates_log_message(self):
|
||||
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(calls[0], 'dubious')
|
||||
|
||||
def test_suspicious_operation_uses_sublogger(self):
|
||||
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(calls[0], 'dubious')
|
||||
|
|
|
@ -394,9 +394,9 @@ class LookupTests(TestCase):
|
|||
['<Article: Article with \ backslash>'])
|
||||
|
||||
def test_exclude(self):
|
||||
a8 = 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))
|
||||
a10 = Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))
|
||||
Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20))
|
||||
Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21))
|
||||
Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22))
|
||||
|
||||
# exclude() is the opposite of filter() when doing lookups:
|
||||
self.assertQuerysetEqual(
|
||||
|
|
|
@ -24,9 +24,9 @@ class M2mThroughTests(TestCase):
|
|||
[]
|
||||
)
|
||||
# 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.
|
||||
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.
|
||||
self.assertQuerysetEqual(
|
||||
self.rock.members.all(), [
|
||||
|
@ -36,9 +36,9 @@ class M2mThroughTests(TestCase):
|
|||
attrgetter("name")
|
||||
)
|
||||
# Now we can add a bunch more Membership objects to test with.
|
||||
m3 = Membership.objects.create(person=self.bob, group=self.roll)
|
||||
m4 = Membership.objects.create(person=self.jim, group=self.roll)
|
||||
m5 = Membership.objects.create(person=self.jane, group=self.roll)
|
||||
Membership.objects.create(person=self.bob, group=self.roll)
|
||||
Membership.objects.create(person=self.jim, group=self.roll)
|
||||
Membership.objects.create(person=self.jane, group=self.roll)
|
||||
# We can get Jim's Group membership as with any ForeignKey.
|
||||
self.assertQuerysetEqual(
|
||||
self.jim.group_set.all(), [
|
||||
|
@ -161,8 +161,8 @@ class M2mThroughTests(TestCase):
|
|||
[]
|
||||
)
|
||||
|
||||
cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock)
|
||||
cm2 = CustomMembership.objects.create(person=self.jim, group=self.rock)
|
||||
CustomMembership.objects.create(person=self.bob, 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.
|
||||
self.assertQuerysetEqual(
|
||||
|
@ -195,7 +195,7 @@ class M2mThroughTests(TestCase):
|
|||
)
|
||||
|
||||
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.
|
||||
self.assertQuerysetEqual(
|
||||
|
@ -209,7 +209,7 @@ class M2mThroughTests(TestCase):
|
|||
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
|
||||
# that addition.
|
||||
|
@ -236,10 +236,10 @@ class M2mThroughTests(TestCase):
|
|||
)
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
m2.invite_reason = "She was just awesome."
|
||||
|
@ -278,8 +278,8 @@ class M2mThroughTests(TestCase):
|
|||
attrgetter("name")
|
||||
)
|
||||
|
||||
cm1 = CustomMembership.objects.create(person=self.bob, group=self.rock)
|
||||
cm2 = CustomMembership.objects.create(person=self.jim, group=self.rock)
|
||||
CustomMembership.objects.create(person=self.bob, 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.
|
||||
self.assertQuerysetEqual(
|
||||
Person.objects.filter(custom__name="Rock"),[
|
||||
|
|
|
@ -56,7 +56,7 @@ class ManyToManyTests(TestCase):
|
|||
with six.assertRaisesRegex(self, TypeError, "'Publication' instance expected, got <Article.*"):
|
||||
a6.publications.add(a5)
|
||||
# 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(),
|
||||
[
|
||||
'<Publication: Highlights for Adults>',
|
||||
|
@ -81,7 +81,7 @@ class ManyToManyTests(TestCase):
|
|||
['<Publication: Science News>'])
|
||||
|
||||
# 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.p2.article_set.all(),
|
||||
[
|
||||
|
|
|
@ -118,10 +118,10 @@ class ManyToOneTests(TestCase):
|
|||
self.assertFalse(hasattr(self.r2.article_set, 'clear'))
|
||||
|
||||
def test_selects(self):
|
||||
new_article = self.r.article_set.create(headline="John's second story",
|
||||
pub_date=datetime.date(2005, 7, 29))
|
||||
new_article2 = self.r2.article_set.create(headline="Paul's story",
|
||||
pub_date=datetime.date(2006, 1, 17))
|
||||
self.r.article_set.create(headline="John's second story",
|
||||
pub_date=datetime.date(2005, 7, 29))
|
||||
self.r2.article_set.create(headline="Paul's story",
|
||||
pub_date=datetime.date(2006, 1, 17))
|
||||
# Reporter objects have access to their related Article objects.
|
||||
self.assertQuerysetEqual(self.r.article_set.all(), [
|
||||
"<Article: John's second story>",
|
||||
|
@ -239,8 +239,8 @@ class ManyToOneTests(TestCase):
|
|||
def test_reverse_selects(self):
|
||||
a3 = Article.objects.create(id=None, headline="Third article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
|
||||
a4 = Article.objects.create(id=None, headline="Fourth article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
|
||||
Article.objects.create(id=None, headline="Fourth article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
|
||||
# Reporters can be queried
|
||||
self.assertQuerysetEqual(Reporter.objects.filter(id__exact=self.r.id),
|
||||
["<Reporter: John Smith>"])
|
||||
|
@ -336,14 +336,14 @@ class ManyToOneTests(TestCase):
|
|||
])
|
||||
|
||||
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))
|
||||
new_article2 = self.r2.article_set.create(headline="Paul's story",
|
||||
pub_date=datetime.date(2006, 1, 17))
|
||||
a3 = Article.objects.create(id=None, headline="Third article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
|
||||
a4 = Article.objects.create(id=None, headline="Fourth article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
|
||||
self.r2.article_set.create(headline="Paul's story",
|
||||
pub_date=datetime.date(2006, 1, 17))
|
||||
Article.objects.create(id=None, headline="Third article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=self.r.id)
|
||||
Article.objects.create(id=None, headline="Fourth article",
|
||||
pub_date=datetime.date(2005, 7, 27), reporter_id=str(self.r.id))
|
||||
# If you delete a reporter, his articles will be deleted.
|
||||
self.assertQuerysetEqual(Article.objects.all(),
|
||||
[
|
||||
|
|
|
@ -87,11 +87,11 @@ class ManyToOneRegressionTests(TestCase):
|
|||
r3 = Record.objects.create(category=c2)
|
||||
r4 = Record.objects.create(category=c2)
|
||||
r5 = Record.objects.create(category=c3)
|
||||
r = Relation.objects.create(left=r1, right=r2)
|
||||
r = Relation.objects.create(left=r3, right=r4)
|
||||
r = Relation.objects.create(left=r1, right=r3)
|
||||
r = Relation.objects.create(left=r5, right=r2)
|
||||
r = Relation.objects.create(left=r3, right=r2)
|
||||
Relation.objects.create(left=r1, right=r2)
|
||||
Relation.objects.create(left=r3, right=r4)
|
||||
Relation.objects.create(left=r1, right=r3)
|
||||
Relation.objects.create(left=r5, right=r2)
|
||||
Relation.objects.create(left=r3, right=r2)
|
||||
|
||||
q1 = Relation.objects.filter(left__category__name__in=['First'], right__category__name__in=['Second'])
|
||||
self.assertQuerysetEqual(q1, ["<Relation: First - Second>"])
|
||||
|
@ -125,7 +125,6 @@ class ManyToOneRegressionTests(TestCase):
|
|||
|
||||
def test_related_null_to_field(self):
|
||||
c1 = Car.objects.create()
|
||||
c2 = Car.objects.create()
|
||||
d1 = Driver.objects.create()
|
||||
self.assertIs(d1.car, None)
|
||||
with self.assertNumQueries(0):
|
||||
|
|
|
@ -117,7 +117,7 @@ class BaseMiddlewareExceptionTest(TestCase):
|
|||
|
||||
def assert_exceptions_handled(self, url, errors, extra_error=None):
|
||||
try:
|
||||
response = self.client.get(url)
|
||||
self.client.get(url)
|
||||
except TestException:
|
||||
# Test client intentionally re-raises any exceptions being raised
|
||||
# during request handling. Hence actual testing that exception was
|
||||
|
|
|
@ -159,7 +159,7 @@ class ImageFieldTests(ImageFieldTestMixin, TestCase):
|
|||
self.assertEqual(p.mugshot.closed, True)
|
||||
|
||||
# After asking for the size, the file should still be closed.
|
||||
_ = p.mugshot.size
|
||||
p.mugshot.size
|
||||
self.assertEqual(p.mugshot.closed, True)
|
||||
|
||||
def test_pickle(self):
|
||||
|
|
|
@ -604,7 +604,7 @@ class PromiseTest(test.TestCase):
|
|||
|
||||
def test_IPAddressField(self):
|
||||
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")
|
||||
self.assertIsInstance(
|
||||
IPAddressField().get_prep_value(lazy_func()),
|
||||
|
|
|
@ -259,7 +259,7 @@ class ModelFormBaseTest(TestCase):
|
|||
['name', 'slug', 'url'])
|
||||
|
||||
def test_missing_fields_attribute(self):
|
||||
with warnings.catch_warnings(record=True) as w:
|
||||
with warnings.catch_warnings(record=True):
|
||||
warnings.simplefilter("always", DeprecationWarning)
|
||||
|
||||
class MissingFieldsForm(forms.ModelForm):
|
||||
|
@ -429,11 +429,11 @@ class ModelFormBaseTest(TestCase):
|
|||
|
||||
# Can't create new form
|
||||
with self.assertRaises(ValueError):
|
||||
f = InvalidModelForm()
|
||||
InvalidModelForm()
|
||||
|
||||
# Even if you provide a model instance
|
||||
with self.assertRaises(ValueError):
|
||||
f = InvalidModelForm(instance=Category)
|
||||
InvalidModelForm(instance=Category)
|
||||
|
||||
def test_subcategory_form(self):
|
||||
class SubCategoryForm(BaseCategoryForm):
|
||||
|
@ -668,7 +668,7 @@ class UniqueTest(TestCase):
|
|||
def test_abstract_inherited_unique(self):
|
||||
title = 'Boss'
|
||||
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})
|
||||
self.assertFalse(form.is_valid())
|
||||
self.assertEqual(len(form.errors), 1)
|
||||
|
@ -677,7 +677,7 @@ class UniqueTest(TestCase):
|
|||
def test_abstract_inherited_unique_together(self):
|
||||
title = 'Boss'
|
||||
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,
|
||||
|
@ -737,7 +737,7 @@ class UniqueTest(TestCase):
|
|||
"""If the date for unique_for_* constraints is excluded from the
|
||||
ModelForm (in this case 'posted' has editable=False, then the
|
||||
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",
|
||||
posted=datetime.datetime(2008, 9, 3, 10, 10, 1))
|
||||
# 'title' has unique_for_date='posted'
|
||||
|
@ -1697,7 +1697,7 @@ class OldFormForXTests(TestCase):
|
|||
|
||||
def test_foreignkeys_which_use_to_field(self):
|
||||
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)
|
||||
|
||||
field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode')
|
||||
|
|
|
@ -369,8 +369,7 @@ class FormFieldCallbackTests(TestCase):
|
|||
widgets = {'name': widget}
|
||||
fields = "__all__"
|
||||
|
||||
_ = modelform_factory(Person, form=BaseForm,
|
||||
formfield_callback=callback)
|
||||
modelform_factory(Person, form=BaseForm, formfield_callback=callback)
|
||||
id_field, name_field = Person._meta.fields
|
||||
|
||||
self.assertEqual(callback_args,
|
||||
|
@ -567,7 +566,7 @@ class TestTicket19733(TestCase):
|
|||
with warnings.catch_warnings(record=True) as w:
|
||||
warnings.simplefilter("always", DeprecationWarning)
|
||||
# This should become an error once deprecation cycle is complete.
|
||||
form = modelform_factory(Person)
|
||||
modelform_factory(Person)
|
||||
self.assertEqual(w[0].category, DeprecationWarning)
|
||||
|
||||
def test_modelform_factory_with_all_fields(self):
|
||||
|
|
|
@ -291,9 +291,9 @@ class ModelFormsetTest(TestCase):
|
|||
# all existing related objects/inlines for a given object to be
|
||||
# displayed, but not allow the creation of new inlines beyond max_num.
|
||||
|
||||
author1 = Author.objects.create(name='Charles Baudelaire')
|
||||
author2 = Author.objects.create(name='Paul Verlaine')
|
||||
author3 = Author.objects.create(name='Walt Whitman')
|
||||
Author.objects.create(name='Charles Baudelaire')
|
||||
Author.objects.create(name='Paul Verlaine')
|
||||
Author.objects.create(name='Walt Whitman')
|
||||
|
||||
qs = Author.objects.order_by('name')
|
||||
|
||||
|
@ -394,8 +394,8 @@ class ModelFormsetTest(TestCase):
|
|||
Test that a queryset can be overridden in the __init__ method.
|
||||
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#changing-the-queryset
|
||||
"""
|
||||
author1 = Author.objects.create(name='Charles Baudelaire')
|
||||
author2 = Author.objects.create(name='Paul Verlaine')
|
||||
Author.objects.create(name='Charles Baudelaire')
|
||||
Author.objects.create(name='Paul Verlaine')
|
||||
|
||||
class BaseAuthorFormSet(BaseModelFormSet):
|
||||
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
|
||||
# instance. This is used in the admin for save_as functionality.
|
||||
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 = {
|
||||
'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
|
||||
# see #18898
|
||||
FormSet = modelformset_factory(AuthorMeeting, fields='__all__')
|
||||
author = Author.objects.create(pk=1, name='Charles Baudelaire')
|
||||
Author.objects.create(pk=1, name='Charles Baudelaire')
|
||||
data = {
|
||||
'form-TOTAL_FORMS': 1,
|
||||
'form-INITIAL_FORMS': 0,
|
||||
|
@ -1195,9 +1195,9 @@ class ModelFormsetTest(TestCase):
|
|||
|
||||
FormSet = inlineformset_factory(Author, Book, extra=0, fields="__all__")
|
||||
author = Author.objects.create(pk=1, name='Charles Baudelaire')
|
||||
book1 = Book.objects.create(pk=1, author=author, title='Les Paradis Artificiels')
|
||||
book2 = 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=1, author=author, title='Les Paradis Artificiels')
|
||||
Book.objects.create(pk=2, author=author, title='Les Fleurs du Mal')
|
||||
Book.objects.create(pk=3, author=author, title='Flowers of Evil')
|
||||
|
||||
book_ids = author.book_set.order_by('id').values_list('id', flat=True)
|
||||
data = {
|
||||
|
|
|
@ -161,8 +161,8 @@ class InlineFormsetTests(TestCase):
|
|||
|
||||
# Instantiate the Form and FormSet to prove
|
||||
# you can create a formset with an instance of None
|
||||
form = Form(instance=None)
|
||||
formset = FormSet(instance=None)
|
||||
Form(instance=None)
|
||||
FormSet(instance=None)
|
||||
|
||||
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."
|
||||
|
|
|
@ -133,7 +133,7 @@ class ModelInheritanceTest(TestCase):
|
|||
def test_issue_7105(self):
|
||||
# Regressions tests for #7105: dates() queries should be able to use
|
||||
# fields from the parent model as easily as the child.
|
||||
obj = Child.objects.create(
|
||||
Child.objects.create(
|
||||
name='child',
|
||||
created=datetime.datetime(2008, 6, 26, 17, 0, 0))
|
||||
datetimes = list(Child.objects.datetimes('created', 'month'))
|
||||
|
@ -159,7 +159,7 @@ class ModelInheritanceTest(TestCase):
|
|||
|
||||
ident = ItalianRestaurant.objects.all()[0].id
|
||||
self.assertEqual(Place.objects.get(pk=ident), place1)
|
||||
xx = Restaurant.objects.create(
|
||||
Restaurant.objects.create(
|
||||
name='a',
|
||||
address='xx',
|
||||
serves_hot_dogs=True,
|
||||
|
|
|
@ -16,8 +16,8 @@ class ModelInheritanceSelectRelatedTests(TestCase):
|
|||
r2 = Restaurant.objects.create(
|
||||
name="Craft", serves_sushi=False, serves_steak=True
|
||||
)
|
||||
p1 = Person.objects.create(name="John", favorite_restaurant=r1)
|
||||
p2 = Person.objects.create(name="Jane", favorite_restaurant=r2)
|
||||
Person.objects.create(name="John", favorite_restaurant=r1)
|
||||
Person.objects.create(name="Jane", favorite_restaurant=r2)
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
Person.objects.order_by("name").select_related(), [
|
||||
|
|
|
@ -217,7 +217,7 @@ class ModelTests(TestCase):
|
|||
|
||||
class ModelValidationTest(TestCase):
|
||||
def test_pk_validation(self):
|
||||
one = NonAutoPK.objects.create(name="one")
|
||||
NonAutoPK.objects.create(name="one")
|
||||
again = NonAutoPK(name="one")
|
||||
self.assertRaises(ValidationError, again.validate_unique)
|
||||
|
||||
|
|
|
@ -405,7 +405,7 @@ class ModelAdminTests(TestCase):
|
|||
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)
|
||||
inline_instances = ma.get_inline_instances(request)
|
||||
fieldsets = list(inline_instances[0].get_fieldsets(request))
|
||||
|
|
|
@ -384,14 +384,12 @@ class QueryTestCase(TestCase):
|
|||
pro = Book.objects.create(title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
|
||||
marty = Person.objects.create(name="Marty Alchin")
|
||||
george = Person.objects.create(name="George Vilches")
|
||||
|
||||
# Create a book and author on the other database
|
||||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4))
|
||||
|
||||
mark = Person.objects.using('other').create(name="Mark Pilgrim")
|
||||
chris = Person.objects.using('other').create(name="Chris Mills")
|
||||
|
||||
# Save the author's favourite books
|
||||
|
@ -431,7 +429,6 @@ class QueryTestCase(TestCase):
|
|||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4))
|
||||
|
||||
mark = Person.objects.using('other').create(name="Mark Pilgrim")
|
||||
chris = Person.objects.using('other').create(name="Chris Mills")
|
||||
|
||||
# Save the author relations
|
||||
|
@ -561,7 +558,7 @@ class QueryTestCase(TestCase):
|
|||
def test_foreign_key_deletion(self):
|
||||
"Cascaded deletions of Foreign Key relations issue queries on the right database"
|
||||
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
|
||||
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",
|
||||
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
|
||||
try:
|
||||
|
@ -822,7 +819,7 @@ class QueryTestCase(TestCase):
|
|||
"Cascaded deletions of Generic Key relations issue queries on the right database"
|
||||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
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
|
||||
self.assertEqual(Book.objects.using('default').count(), 0)
|
||||
|
@ -843,7 +840,7 @@ class QueryTestCase(TestCase):
|
|||
|
||||
def test_ordering(self):
|
||||
"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))
|
||||
|
||||
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()"
|
||||
# Create a book and author on the other database
|
||||
mark = Person.objects.using('other').create(name="Mark Pilgrim")
|
||||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4),
|
||||
editor=mark)
|
||||
Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4),
|
||||
editor=mark)
|
||||
|
||||
# Retrieve the Person using select_related()
|
||||
book = Book.objects.using('other').select_related('editor').get(title="Dive into Python")
|
||||
|
@ -1033,8 +1030,8 @@ class RouterTestCase(TestCase):
|
|||
pro.authors = [marty]
|
||||
|
||||
# Create a book and author on the other database
|
||||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4))
|
||||
Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4))
|
||||
|
||||
# An update query will be routed to the default database
|
||||
Book.objects.filter(title='Pro Django').update(pages=200)
|
||||
|
@ -1443,8 +1440,6 @@ class RouterTestCase(TestCase):
|
|||
published=datetime.date(2008, 12, 16))
|
||||
|
||||
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_manager('default').db, 'default')
|
||||
|
@ -1457,9 +1452,9 @@ class RouterTestCase(TestCase):
|
|||
def test_foreign_key_managers(self):
|
||||
"FK reverse relations are represented by managers, and can be controlled like managers"
|
||||
marty = Person.objects.using('other').create(pk=1, name="Marty Alchin")
|
||||
pro = Book.objects.using('other').create(pk=1, title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16),
|
||||
editor=marty)
|
||||
Book.objects.using('other').create(pk=1, title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16),
|
||||
editor=marty)
|
||||
|
||||
self.assertEqual(marty.edited.db, 'other')
|
||||
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",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
|
||||
review1 = Review.objects.using('other').create(source="Python Monthly",
|
||||
content_object=pro)
|
||||
Review.objects.using('other').create(source="Python Monthly",
|
||||
content_object=pro)
|
||||
|
||||
self.assertEqual(pro.reviews.db, 'other')
|
||||
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
|
||||
|
||||
mark = Person.objects.using('other').create(name="Mark Pilgrim")
|
||||
dive = Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4),
|
||||
editor=mark)
|
||||
Book.objects.using('other').create(title="Dive into Python",
|
||||
published=datetime.date(2009, 5, 4),
|
||||
editor=mark)
|
||||
|
||||
sub = Person.objects.filter(name='Mark Pilgrim')
|
||||
qs = Book.objects.filter(editor__in=sub)
|
||||
|
@ -1857,7 +1852,7 @@ class RouterModelArgumentTestCase(TestCase):
|
|||
|
||||
def test_foreignkey_collection(self):
|
||||
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
|
||||
person.delete()
|
||||
|
||||
|
@ -1967,7 +1962,7 @@ class RouteForWriteTestCase(TestCase):
|
|||
|
||||
def test_reverse_fk_update(self):
|
||||
owner = Person.objects.create(name='Someone')
|
||||
pet = Pet.objects.create(name='fido', owner=owner)
|
||||
Pet.objects.create(name='fido', owner=owner)
|
||||
self.enable_router()
|
||||
try:
|
||||
owner.pet_set.update(name='max')
|
||||
|
@ -2019,7 +2014,7 @@ class RouteForWriteTestCase(TestCase):
|
|||
self.assertEqual(e.hints, {'instance': book})
|
||||
|
||||
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",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
self.enable_router()
|
||||
|
@ -2103,8 +2098,8 @@ class RouteForWriteTestCase(TestCase):
|
|||
|
||||
def test_reverse_m2m_get_or_create(self):
|
||||
auth = Person.objects.create(name='Someone')
|
||||
book = Book.objects.create(title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
Book.objects.create(title="Pro Django",
|
||||
published=datetime.date(2008, 12, 16))
|
||||
self.enable_router()
|
||||
try:
|
||||
auth.book_set.get_or_create(title="New Book", published=datetime.datetime.now())
|
||||
|
|
|
@ -12,7 +12,7 @@ class MutuallyReferentialTests(TestCase):
|
|||
|
||||
# Create some children
|
||||
c = q.child_set.create(name='Charles')
|
||||
e = q.child_set.create(name='Edward')
|
||||
q.child_set.create(name='Edward')
|
||||
|
||||
# Set the best child
|
||||
# No assertion require here; if basic assignment and
|
||||
|
|
|
@ -32,8 +32,8 @@ class NestedForeignKeysTests(TestCase):
|
|||
# This test failed in #16715 because in some cases INNER JOIN was selected
|
||||
# for the second foreign key relation instead of LEFT OUTER JOIN.
|
||||
def testInheritance(self):
|
||||
some_event = Event.objects.create()
|
||||
screening = Screening.objects.create(movie=self.movie)
|
||||
Event.objects.create()
|
||||
Screening.objects.create(movie=self.movie)
|
||||
|
||||
self.assertEqual(len(Event.objects.all()), 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.
|
||||
def testInheritanceNullFK(self):
|
||||
some_event = Event.objects.create()
|
||||
screening = ScreeningNullFK.objects.create(movie=None)
|
||||
screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie)
|
||||
Event.objects.create()
|
||||
ScreeningNullFK.objects.create(movie=None)
|
||||
ScreeningNullFK.objects.create(movie=self.movie)
|
||||
|
||||
self.assertEqual(len(Event.objects.all()), 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
|
||||
# for the second foreign key relation instead of LEFT OUTER JOIN.
|
||||
def testExplicitForeignKey(self):
|
||||
package = Package.objects.create()
|
||||
Package.objects.create()
|
||||
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.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.
|
||||
def testExplicitForeignKeyNullFK(self):
|
||||
package = PackageNullFK.objects.create()
|
||||
PackageNullFK.objects.create()
|
||||
screening = ScreeningNullFK.objects.create(movie=None)
|
||||
screening_with_movie = ScreeningNullFK.objects.create(movie=self.movie)
|
||||
package_with_screening = PackageNullFK.objects.create(screening=screening)
|
||||
package_with_screening_with_movie = PackageNullFK.objects.create(screening=screening_with_movie)
|
||||
PackageNullFK.objects.create(screening=screening)
|
||||
PackageNullFK.objects.create(screening=screening_with_movie)
|
||||
|
||||
self.assertEqual(len(PackageNullFK.objects.all()), 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)
|
||||
|
||||
def testInheritance(self):
|
||||
some_event = Event.objects.create()
|
||||
screening = Screening.objects.create(movie=self.movie)
|
||||
Event.objects.create()
|
||||
Screening.objects.create(movie=self.movie)
|
||||
|
||||
self.assertEqual(len(Event.objects.all()), 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)
|
||||
|
||||
def testExplicitForeignKey(self):
|
||||
package = Package.objects.create()
|
||||
Package.objects.create()
|
||||
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.select_related('screening__movie__director')), 2)
|
||||
|
|
|
@ -15,9 +15,9 @@ class NullFkOrderingTests(TestCase):
|
|||
"""
|
||||
author_1 = Author.objects.create(name='Tom Jones')
|
||||
author_2 = Author.objects.create(name='Bob Smith')
|
||||
article_1 = 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_3 = Article.objects.create(author=author_2, title='This article written by Bob Smith')
|
||||
Article.objects.create(title='No author on this article')
|
||||
Article.objects.create(author=author_1, title='This article written by Tom Jones')
|
||||
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
|
||||
# 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')
|
||||
f = Forum.objects.create(system_info=s, forum_name='First forum')
|
||||
p = Post.objects.create(forum=f, title='First Post')
|
||||
c1 = Comment.objects.create(post=p, comment_text='My first comment')
|
||||
c2 = Comment.objects.create(comment_text='My second comment')
|
||||
Comment.objects.create(post=p, comment_text='My first comment')
|
||||
Comment.objects.create(comment_text='My second comment')
|
||||
s2 = SystemInfo.objects.create(system_name='More System Info')
|
||||
f2 = Forum.objects.create(system_info=s2, forum_name='Second forum')
|
||||
p2 = Post.objects.create(forum=f2, title='Second Post')
|
||||
c3 = Comment.objects.create(comment_text='Another first comment')
|
||||
c4 = Comment.objects.create(post=p2, comment_text='Another second comment')
|
||||
Comment.objects.create(comment_text='Another first comment')
|
||||
Comment.objects.create(post=p2, comment_text='Another second comment')
|
||||
|
||||
# We have to test this carefully. Some databases sort NULL values before
|
||||
# everything else, some sort them afterwards. So we extract the ordered list
|
||||
|
|
|
@ -63,7 +63,7 @@ class NullQueriesTests(TestCase):
|
|||
['<OuterA: OuterA object>']
|
||||
)
|
||||
|
||||
inner_obj = Inner.objects.create(first=obj)
|
||||
Inner.objects.create(first=obj)
|
||||
self.assertQuerysetEqual(
|
||||
Inner.objects.filter(first__inner__third=None),
|
||||
['<Inner: Inner object>']
|
||||
|
@ -71,7 +71,7 @@ class NullQueriesTests(TestCase):
|
|||
|
||||
# Ticket #13815: check if <reverse>_isnull=False does not produce
|
||||
# faulty empty lists
|
||||
objB = OuterB.objects.create(data="reverse")
|
||||
OuterB.objects.create(data="reverse")
|
||||
self.assertQuerysetEqual(
|
||||
OuterB.objects.filter(inner__isnull=False),
|
||||
[]
|
||||
|
|
|
@ -68,6 +68,6 @@ class OrderWithRespectToTests(TestCase):
|
|||
p2 = Post.objects.create(title='2')
|
||||
p1_1 = Post.objects.create(title="1.1", 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)
|
||||
self.assertEqual(p1.get_post_order(), [p1_1.pk, p1_2.pk, p1_3.pk])
|
||||
|
|
|
@ -10,13 +10,13 @@ from .models import Article, ArticlePKOrdering
|
|||
|
||||
class OrderingTests(TestCase):
|
||||
def test_basic(self):
|
||||
a1 = Article.objects.create(
|
||||
Article.objects.create(
|
||||
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)
|
||||
)
|
||||
a3 = Article.objects.create(
|
||||
Article.objects.create(
|
||||
headline="Article 3", pub_date=datetime(2005, 7, 27)
|
||||
)
|
||||
a4 = Article.objects.create(
|
||||
|
@ -143,16 +143,16 @@ class OrderingTests(TestCase):
|
|||
Ensure that 'pk' works as an ordering option in Meta.
|
||||
Refs #8291.
|
||||
"""
|
||||
a1 = ArticlePKOrdering.objects.create(
|
||||
ArticlePKOrdering.objects.create(
|
||||
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)
|
||||
)
|
||||
a3 = ArticlePKOrdering.objects.create(
|
||||
ArticlePKOrdering.objects.create(
|
||||
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)
|
||||
)
|
||||
|
||||
|
|
|
@ -64,8 +64,8 @@ class PrefetchRelatedTests(TestCase):
|
|||
|
||||
def test_foreignkey_reverse(self):
|
||||
with self.assertNumQueries(2):
|
||||
lists = [list(b.first_time_authors.all())
|
||||
for b in Book.objects.prefetch_related('first_time_authors')]
|
||||
[list(b.first_time_authors.all())
|
||||
for b in Book.objects.prefetch_related('first_time_authors')]
|
||||
|
||||
self.assertQuerysetEqual(self.book2.authors.all(), ["<Author: Charlotte>"])
|
||||
|
||||
|
@ -79,22 +79,20 @@ class PrefetchRelatedTests(TestCase):
|
|||
|
||||
def test_survives_clone(self):
|
||||
with self.assertNumQueries(2):
|
||||
lists = [list(b.first_time_authors.all())
|
||||
for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)]
|
||||
[list(b.first_time_authors.all())
|
||||
for b in Book.objects.prefetch_related('first_time_authors').exclude(id=1000)]
|
||||
|
||||
def test_len(self):
|
||||
with self.assertNumQueries(2):
|
||||
qs = Book.objects.prefetch_related('first_time_authors')
|
||||
length = len(qs)
|
||||
lists = [list(b.first_time_authors.all())
|
||||
for b in qs]
|
||||
len(qs)
|
||||
[list(b.first_time_authors.all()) for b in qs]
|
||||
|
||||
def test_bool(self):
|
||||
with self.assertNumQueries(2):
|
||||
qs = Book.objects.prefetch_related('first_time_authors')
|
||||
x = bool(qs)
|
||||
lists = [list(b.first_time_authors.all())
|
||||
for b in qs]
|
||||
bool(qs)
|
||||
[list(b.first_time_authors.all()) for b in qs]
|
||||
|
||||
def test_count(self):
|
||||
with self.assertNumQueries(2):
|
||||
|
@ -123,7 +121,7 @@ class PrefetchRelatedTests(TestCase):
|
|||
with self.assertNumQueries(5):
|
||||
with_prefetch = Author.objects.prefetch_related('books')
|
||||
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):
|
||||
"""
|
||||
|
@ -321,8 +319,8 @@ class GenericRelationTests(TestCase):
|
|||
|
||||
def test_generic_relation(self):
|
||||
bookmark = Bookmark.objects.create(url='http://www.djangoproject.com/')
|
||||
t1 = TaggedItem.objects.create(content_object=bookmark, tag='django')
|
||||
t2 = TaggedItem.objects.create(content_object=bookmark, tag='python')
|
||||
TaggedItem.objects.create(content_object=bookmark, tag='django')
|
||||
TaggedItem.objects.create(content_object=bookmark, tag='python')
|
||||
|
||||
with self.assertNumQueries(2):
|
||||
tags = [t.tag for b in Bookmark.objects.prefetch_related('tags')
|
||||
|
@ -331,8 +329,8 @@ class GenericRelationTests(TestCase):
|
|||
|
||||
def test_charfield_GFK(self):
|
||||
b = Bookmark.objects.create(url='http://www.djangoproject.com/')
|
||||
t1 = 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, tag='django')
|
||||
TaggedItem.objects.create(content_object=b, favorite=b, tag='python')
|
||||
|
||||
with self.assertNumQueries(3):
|
||||
bookmark = Bookmark.objects.filter(pk=b.pk).prefetch_related('tags', 'favorite_tags')[0]
|
||||
|
@ -497,8 +495,8 @@ class NullableTest(TestCase):
|
|||
|
||||
def setUp(self):
|
||||
boss = Employee.objects.create(name="Peter")
|
||||
worker1 = Employee.objects.create(name="Joe", boss=boss)
|
||||
worker2 = Employee.objects.create(name="Angela", boss=boss)
|
||||
Employee.objects.create(name="Joe", boss=boss)
|
||||
Employee.objects.create(name="Angela", boss=boss)
|
||||
|
||||
def test_traverse_nullable(self):
|
||||
# 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")
|
||||
book2 = B.create(title="Sense and Sensibility")
|
||||
|
||||
author1 = A.create(name="Charlotte Bronte", first_book=book1)
|
||||
author2 = A.create(name="Jane Austen", first_book=book2)
|
||||
A.create(name="Charlotte Bronte", first_book=book1)
|
||||
A.create(name="Jane Austen", first_book=book2)
|
||||
|
||||
# Forward
|
||||
with self.assertNumQueries(2, using='other'):
|
||||
|
@ -613,9 +611,9 @@ class MultiDbTests(TestCase):
|
|||
B = BookWithYear.objects.using('other')
|
||||
A = AuthorWithAge.objects.using('other')
|
||||
book1 = B.create(title="Poems", published_year=2010)
|
||||
book2 = B.create(title="More poems", published_year=2011)
|
||||
author1 = A.create(name='Jane', first_book=book1, age=50)
|
||||
author2 = A.create(name='Tom', first_book=book1, age=49)
|
||||
B.create(title="More poems", published_year=2011)
|
||||
A.create(name='Jane', first_book=book1, age=50)
|
||||
A.create(name='Tom', first_book=book1, age=49)
|
||||
|
||||
# parent link
|
||||
with self.assertNumQueries(2, using='other'):
|
||||
|
|
|
@ -105,8 +105,8 @@ class ProxyModelTests(TestCase):
|
|||
name='Zathras'
|
||||
)
|
||||
|
||||
sp1 = StatusPerson.objects.create(name='Bazza Jr.')
|
||||
sp2 = StatusPerson.objects.create(name='Foo Jr.')
|
||||
StatusPerson.objects.create(name='Bazza Jr.')
|
||||
StatusPerson.objects.create(name='Foo Jr.')
|
||||
max_id = Person.objects.aggregate(max_id=models.Max('id'))['max_id']
|
||||
|
||||
self.assertRaises(Person.MultipleObjectsReturned,
|
||||
|
@ -232,7 +232,7 @@ class ProxyModelTests(TestCase):
|
|||
signals.pre_save.connect(h3, sender=Person)
|
||||
signals.post_save.connect(h4, sender=Person)
|
||||
|
||||
dino = MyPerson.objects.create(name="dino")
|
||||
MyPerson.objects.create(name="dino")
|
||||
self.assertEqual(output, [
|
||||
'MyPerson pre save',
|
||||
'MyPerson post save'
|
||||
|
@ -246,7 +246,7 @@ class ProxyModelTests(TestCase):
|
|||
signals.pre_save.connect(h5, sender=MyPersonProxy)
|
||||
signals.post_save.connect(h6, sender=MyPersonProxy)
|
||||
|
||||
dino = MyPersonProxy.objects.create(name="pebbles")
|
||||
MyPersonProxy.objects.create(name="pebbles")
|
||||
|
||||
self.assertEqual(output, [
|
||||
'MyPersonProxy pre save',
|
||||
|
@ -303,7 +303,7 @@ class ProxyModelTests(TestCase):
|
|||
querysets.
|
||||
"""
|
||||
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()]
|
||||
self.assertEqual(resp, ['New South Wales'])
|
||||
|
|
|
@ -713,7 +713,7 @@ class Queries1Tests(BaseQuerysetTest):
|
|||
|
||||
# Pickling of DateQuerySets used to fail
|
||||
qs = Item.objects.datetimes('created', 'month')
|
||||
_ = pickle.loads(pickle.dumps(qs))
|
||||
pickle.loads(pickle.dumps(qs))
|
||||
|
||||
def test_ticket9997(self):
|
||||
# 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",
|
||||
special_name="special2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c1)
|
||||
CategoryItem.objects.create(category=c1)
|
||||
ci2 = CategoryItem.objects.create(category=c2)
|
||||
ci3 = CategoryItem.objects.create(category=c3)
|
||||
|
||||
|
@ -1399,8 +1399,8 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
special_name="special2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c1)
|
||||
ci2 = CategoryItem.objects.create(category=c2)
|
||||
ci3 = CategoryItem.objects.create(category=c3)
|
||||
CategoryItem.objects.create(category=c2)
|
||||
CategoryItem.objects.create(category=c3)
|
||||
|
||||
qs = CategoryItem.objects.exclude(category__specialcategory__isnull=False)
|
||||
self.assertEqual(qs.count(), 1)
|
||||
|
@ -1414,8 +1414,8 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
special_name="special2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c1)
|
||||
ci2 = CategoryItem.objects.create(category=c2)
|
||||
ci3 = CategoryItem.objects.create(category=c3)
|
||||
CategoryItem.objects.create(category=c2)
|
||||
CategoryItem.objects.create(category=c3)
|
||||
|
||||
qs = CategoryItem.objects.filter(category__specialcategory__isnull=True)
|
||||
self.assertEqual(qs.count(), 1)
|
||||
|
@ -1428,7 +1428,7 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
c3 = SpecialCategory.objects.create(name="named category2",
|
||||
special_name="special2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c1)
|
||||
CategoryItem.objects.create(category=c1)
|
||||
ci2 = CategoryItem.objects.create(category=c2)
|
||||
ci3 = CategoryItem.objects.create(category=c3)
|
||||
|
||||
|
@ -1441,10 +1441,10 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
c0 = SimpleCategory.objects.create(name="cat0")
|
||||
c1 = SimpleCategory.objects.create(name="category1")
|
||||
|
||||
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
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)
|
||||
ci3 = CategoryItem.objects.create(category=c1)
|
||||
|
||||
|
@ -1457,12 +1457,12 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
c0 = SimpleCategory.objects.create(name="cat0")
|
||||
c1 = SimpleCategory.objects.create(name="category1")
|
||||
|
||||
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c)
|
||||
ci2 = CategoryItem.objects.create(category=c0)
|
||||
ci3 = CategoryItem.objects.create(category=c1)
|
||||
CategoryItem.objects.create(category=c0)
|
||||
CategoryItem.objects.create(category=c1)
|
||||
|
||||
qs = CategoryItem.objects.exclude(category__onetoonecategory__isnull=False)
|
||||
self.assertEqual(qs.count(), 1)
|
||||
|
@ -1473,12 +1473,12 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
c0 = SimpleCategory.objects.create(name="cat0")
|
||||
c1 = SimpleCategory.objects.create(name="category1")
|
||||
|
||||
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
|
||||
ci1 = CategoryItem.objects.create(category=c)
|
||||
ci2 = CategoryItem.objects.create(category=c0)
|
||||
ci3 = CategoryItem.objects.create(category=c1)
|
||||
CategoryItem.objects.create(category=c0)
|
||||
CategoryItem.objects.create(category=c1)
|
||||
|
||||
qs = CategoryItem.objects.filter(category__onetoonecategory__isnull=True)
|
||||
self.assertEqual(qs.count(), 1)
|
||||
|
@ -1489,10 +1489,10 @@ class Queries4Tests(BaseQuerysetTest):
|
|||
c0 = SimpleCategory.objects.create(name="cat0")
|
||||
c1 = SimpleCategory.objects.create(name="category1")
|
||||
|
||||
c2 = OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
c3 = OneToOneCategory.objects.create(category = c0, new_name="new2")
|
||||
OneToOneCategory.objects.create(category = c1, new_name="new1")
|
||||
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)
|
||||
ci3 = CategoryItem.objects.create(category=c1)
|
||||
|
||||
|
@ -1712,14 +1712,14 @@ class Queries6Tests(TestCase):
|
|||
def setUp(self):
|
||||
generic = NamedCategory.objects.create(name="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)
|
||||
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)
|
||||
ann1 = Annotation.objects.create(name='a1', tag=t1)
|
||||
ann1.notes.add(n1)
|
||||
ann2 = Annotation.objects.create(name='a2', tag=t4)
|
||||
Annotation.objects.create(name='a2', tag=t4)
|
||||
|
||||
def test_parallel_iterators(self):
|
||||
# Test that parallel iterators work.
|
||||
|
@ -1794,7 +1794,7 @@ class Queries6Tests(TestCase):
|
|||
|
||||
class RawQueriesTests(TestCase):
|
||||
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):
|
||||
# Test representation of raw query with one or few parameters passed as list
|
||||
|
@ -1827,8 +1827,8 @@ class ComparisonTests(TestCase):
|
|||
|
||||
def test_ticket8597(self):
|
||||
# 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="x%y", 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)
|
||||
self.assertQuerysetEqual(
|
||||
Item.objects.filter(name__iexact="A_b"),
|
||||
['<Item: a_b>']
|
||||
|
@ -2129,7 +2129,7 @@ class WeirdQuerysetSlicingTests(BaseQuerysetTest):
|
|||
class EscapingTests(TestCase):
|
||||
def test_ticket_7302(self):
|
||||
# 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)
|
||||
self.assertQuerysetEqual(
|
||||
ReservedName.objects.all().order_by('order'),
|
||||
|
@ -2209,10 +2209,10 @@ class ConditionalTests(BaseQuerysetTest):
|
|||
def setUp(self):
|
||||
generic = NamedCategory.objects.create(name="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)
|
||||
t4 = Tag.objects.create(name='t4', parent=t3)
|
||||
t5 = Tag.objects.create(name='t5', parent=t3)
|
||||
Tag.objects.create(name='t4', parent=t3)
|
||||
Tag.objects.create(name='t5', parent=t3)
|
||||
|
||||
def test_infinite_loop(self):
|
||||
# If you're not careful, it's possible to introduce infinite loops via
|
||||
|
@ -2474,8 +2474,8 @@ class Exclude15786(TestCase):
|
|||
def test_ticket15786(self):
|
||||
c1 = SimpleCategory.objects.create(name='c1')
|
||||
c2 = SimpleCategory.objects.create(name='c2')
|
||||
o2o1 = OneToOneCategory.objects.create(category=c1)
|
||||
o2o2 = OneToOneCategory.objects.create(category=c2)
|
||||
OneToOneCategory.objects.create(category=c1)
|
||||
OneToOneCategory.objects.create(category=c2)
|
||||
rel = CategoryRelationship.objects.create(first=c1, second=c2)
|
||||
self.assertEqual(
|
||||
CategoryRelationship.objects.exclude(
|
||||
|
|
|
@ -390,7 +390,7 @@ class RequestsTests(SimpleTestCase):
|
|||
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
|
||||
'CONTENT_LENGTH': len(payload),
|
||||
'wsgi.input': payload})
|
||||
raw_data = request.body
|
||||
request.body # evaluate
|
||||
self.assertEqual(request.POST, {'name': ['value']})
|
||||
|
||||
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_LENGTH': len(payload),
|
||||
'wsgi.input': payload})
|
||||
raw_data = request.body
|
||||
request.body # evaluate
|
||||
self.assertEqual(request.read(1), b'n')
|
||||
self.assertEqual(request.POST, {'name': ['value']})
|
||||
|
||||
|
@ -423,7 +423,7 @@ class RequestsTests(SimpleTestCase):
|
|||
'CONTENT_TYPE': 'multipart/form-data; boundary=boundary',
|
||||
'CONTENT_LENGTH': len(payload),
|
||||
'wsgi.input': payload})
|
||||
raw_data = request.body
|
||||
request.body # evaluate
|
||||
# Consume enough data to mess up the parsing:
|
||||
self.assertEqual(request.read(13), b'--boundary\r\nC')
|
||||
self.assertEqual(request.POST, {'name': ['value']})
|
||||
|
|
|
@ -10,10 +10,10 @@ from .models import Thing
|
|||
class ReservedNameTests(TestCase):
|
||||
def generate(self):
|
||||
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')
|
||||
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)
|
||||
|
||||
def test_simple(self):
|
||||
|
|
|
@ -19,7 +19,7 @@ class ReverseLookupTests(TestCase):
|
|||
question="What's the second question?",
|
||||
creator=jim
|
||||
)
|
||||
new_choice = Choice.objects.create(
|
||||
Choice.objects.create(
|
||||
poll=first_poll,
|
||||
related_poll=second_poll,
|
||||
name="This is the answer."
|
||||
|
|
|
@ -655,7 +655,7 @@ class SchemaTests(TransactionTestCase):
|
|||
class SomeError(Exception):
|
||||
pass
|
||||
try:
|
||||
with connection.schema_editor() as editor:
|
||||
with connection.schema_editor():
|
||||
raise SomeError
|
||||
except SomeError:
|
||||
self.assertFalse(connection.in_atomic_block)
|
||||
|
|
|
@ -254,7 +254,7 @@ class SelectForUpdateTests(TransactionTestCase):
|
|||
means that it will be either committed or rolled back by Django,
|
||||
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())
|
||||
|
||||
@skipUnlessDBFeature('has_select_for_update')
|
||||
|
|
|
@ -12,12 +12,11 @@ from .models import (User, UserProfile, UserStat, UserStatResult, StatDetails,
|
|||
class ReverseSelectRelatedTestCase(TestCase):
|
||||
def setUp(self):
|
||||
user = User.objects.create(username="test")
|
||||
userprofile = UserProfile.objects.create(user=user, state="KS",
|
||||
city="Lawrence")
|
||||
UserProfile.objects.create(user=user, state="KS", city="Lawrence")
|
||||
results = UserStatResult.objects.create(results='first results')
|
||||
userstat = UserStat.objects.create(user=user, posts=150,
|
||||
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")
|
||||
results2 = UserStatResult.objects.create(results='moar results')
|
||||
|
|
|
@ -61,7 +61,7 @@ class SelectRelatedRegressTests(TestCase):
|
|||
s = Student.objects.create(person = usp)
|
||||
o = Organizer.objects.create(person = uop)
|
||||
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]
|
||||
self.assertEqual(e_related.std.person.user.name, "std")
|
||||
|
@ -77,7 +77,7 @@ class SelectRelatedRegressTests(TestCase):
|
|||
for country before getting status.
|
||||
"""
|
||||
|
||||
australia = Country.objects.create(name='Australia')
|
||||
Country.objects.create(name='Australia')
|
||||
active = ClientStatus.objects.create(name='active')
|
||||
client = Client.objects.create(name='client', status=active)
|
||||
|
||||
|
@ -92,8 +92,8 @@ class SelectRelatedRegressTests(TestCase):
|
|||
def test_multi_table_inheritance(self):
|
||||
""" Exercising select_related() with multi-table model inheritance. """
|
||||
c1 = Child.objects.create(name="child1", value=42)
|
||||
i1 = Item.objects.create(name="item1", child=c1)
|
||||
i2 = Item.objects.create(name="item2")
|
||||
Item.objects.create(name="item1", child=c1)
|
||||
Item.objects.create(name="item2")
|
||||
|
||||
self.assertQuerysetEqual(
|
||||
Item.objects.select_related("child").order_by("name"),
|
||||
|
@ -111,14 +111,14 @@ class SelectRelatedRegressTests(TestCase):
|
|||
active = ClientStatus.objects.create(name='active')
|
||||
|
||||
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')
|
||||
|
||||
self.assertEqual(burke.name, 'Brian Burke')
|
||||
self.assertEqual(burke.state.name, 'Western Australia')
|
||||
|
||||
# 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')
|
||||
|
||||
self.assertEqual(troy.name, 'Troy Buswell')
|
||||
|
@ -168,7 +168,7 @@ class SelectRelatedRegressTests(TestCase):
|
|||
|
||||
"""
|
||||
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.select_related()[0].mother.name, 'Hen')
|
||||
|
|
|
@ -198,7 +198,7 @@ class SerializersTestBase(object):
|
|||
mv.save()
|
||||
|
||||
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):
|
||||
"""
|
||||
|
|
|
@ -144,8 +144,8 @@ def m2m_compare(testcase, pk, klass, data):
|
|||
testcase.assertEqual(data, [obj.id for obj in instance.data.order_by('id')])
|
||||
|
||||
def im2m_compare(testcase, pk, klass, data):
|
||||
instance = klass.objects.get(id=pk)
|
||||
#actually nothing else to check, the instance just should exist
|
||||
klass.objects.get(id=pk)
|
||||
# actually nothing else to check, the instance just should exist
|
||||
|
||||
def im_compare(testcase, pk, klass, data):
|
||||
instance = klass.objects.get(id=pk)
|
||||
|
@ -478,7 +478,7 @@ def naturalKeySerializerTest(format, self):
|
|||
instance_count[klass] = klass.objects.count()
|
||||
|
||||
# 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")
|
||||
# Serialize the test database
|
||||
serialized_data = serializers.serialize(format, objects, indent=2,
|
||||
|
|
|
@ -172,7 +172,7 @@ class SignalTests(TestCase):
|
|||
a, b = MyReceiver(1), MyReceiver(2)
|
||||
signals.post_save.connect(sender=Person, receiver=a)
|
||||
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(b._run)
|
||||
|
|
|
@ -28,9 +28,9 @@ class SitesFrameworkTestCase(TestCase):
|
|||
self.assertEqual(CustomArticle.on_site.all().get(), article)
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
|
|
@ -561,7 +561,7 @@ class TestCollectionCachedStorage(BaseCollectionTestCase,
|
|||
"""
|
||||
finders._finders.clear()
|
||||
err = six.StringIO()
|
||||
with self.assertRaises(Exception) as cm:
|
||||
with self.assertRaises(Exception):
|
||||
call_command('collectstatic', interactive=False, verbosity=0, stderr=err)
|
||||
self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
|
||||
|
||||
|
|
|
@ -187,7 +187,7 @@ class SimpleTemplateResponseTest(TestCase):
|
|||
response.render()
|
||||
pickled_response = pickle.dumps(response)
|
||||
unpickled_response = pickle.loads(pickled_response)
|
||||
repickled_response = pickle.dumps(unpickled_response)
|
||||
pickle.dumps(unpickled_response)
|
||||
|
||||
def test_pickling_cookie(self):
|
||||
response = SimpleTemplateResponse('first/test.html', {
|
||||
|
@ -293,7 +293,7 @@ class TemplateResponseTest(TestCase):
|
|||
response.render()
|
||||
pickled_response = pickle.dumps(response)
|
||||
unpickled_response = pickle.loads(pickled_response)
|
||||
repickled_response = pickle.dumps(unpickled_response)
|
||||
pickle.dumps(unpickled_response)
|
||||
|
||||
|
||||
class CustomURLConfTest(TestCase):
|
||||
|
|
|
@ -20,10 +20,10 @@ class UnicodeTests(TestCase):
|
|||
self.assertRaises(TemplateEncodingError, Template, s)
|
||||
|
||||
# Contexts can be constructed from unicode or UTF-8 bytestrings.
|
||||
c1 = Context({b"var": b"foo"})
|
||||
c2 = Context({"var": b"foo"})
|
||||
Context({b"var": b"foo"})
|
||||
Context({"var": b"foo"})
|
||||
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,
|
||||
# they all render the same (and are returned as unicode objects and
|
||||
|
|
|
@ -370,7 +370,6 @@ class TemplateLoaderTests(TestCase):
|
|||
template that does not exist does not raise an exception at parse
|
||||
time.
|
||||
"""
|
||||
ctx = Context()
|
||||
tmpl = Template('{% include "this_does_not_exist.html" %}')
|
||||
self.assertIsInstance(tmpl, Template)
|
||||
|
||||
|
@ -440,7 +439,7 @@ class TemplateRegressionTests(TestCase):
|
|||
# Regression test for #19392
|
||||
with six.assertRaisesRegex(self, template.TemplateSyntaxError,
|
||||
"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)
|
||||
def test_no_wrapped_exception(self):
|
||||
|
@ -458,7 +457,7 @@ class TemplateRegressionTests(TestCase):
|
|||
def test_invalid_block_suggestion(self):
|
||||
# See #7876
|
||||
try:
|
||||
t = Template("{% if 1 %}lala{% endblock %}{% endif %}")
|
||||
Template("{% if 1 %}lala{% endblock %}{% endif %}")
|
||||
except TemplateSyntaxError as e:
|
||||
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
|
||||
sys.path.append(egg_name)
|
||||
settings.INSTALLED_APPS = ('tagsegg',)
|
||||
t = template.Template(ttext)
|
||||
template.Template(ttext)
|
||||
|
||||
|
||||
class RequestContextTests(unittest.TestCase):
|
||||
|
|
|
@ -419,7 +419,7 @@ class ClientTest(TestCase):
|
|||
pass
|
||||
|
||||
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
|
||||
self.assertEqual(self.client.session['tobacconist'], 'hovercraft')
|
||||
|
|
|
@ -810,7 +810,7 @@ class ExceptionTests(TestCase):
|
|||
login = self.client.login(username='testclient',password='password')
|
||||
self.assertTrue(login, 'Could not log in')
|
||||
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")
|
||||
except CustomTestException:
|
||||
pass
|
||||
|
@ -840,7 +840,7 @@ class TemplateExceptionTests(TestCase):
|
|||
def test_bad_404_template(self):
|
||||
"Errors found when rendering 404 error templates are re-raised"
|
||||
try:
|
||||
response = self.client.get("/no_such_view/")
|
||||
self.client.get("/no_such_view/")
|
||||
self.fail("Should get error about syntax error in template")
|
||||
except TemplateSyntaxError:
|
||||
pass
|
||||
|
|
|
@ -35,7 +35,7 @@ def request_data(request, template='base.html', data='sausage'):
|
|||
"A simple view that returns the request data in the context"
|
||||
|
||||
# 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")
|
||||
request_foo = request.REQUEST.get('foo')
|
||||
request_bar = request.REQUEST.get('bar')
|
||||
|
|
|
@ -257,7 +257,7 @@ class LegacyDatabaseTests(TestCase):
|
|||
def test_filter_date_field_with_aware_datetime(self):
|
||||
# Regression test for #17742
|
||||
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
|
||||
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
|
||||
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):
|
||||
# Regression test for #17742
|
||||
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
|
||||
dt = datetime.datetime(2011, 9, 1, 22, 30, 0, tzinfo=UTC)
|
||||
self.assertFalse(AllDayEvent.objects.filter(day__gte=dt).exists())
|
||||
|
|
|
@ -228,7 +228,7 @@ class ResolverTests(unittest.TestCase):
|
|||
proxy_url = reverse_lazy('named-url1', urlconf=urls)
|
||||
resolver = get_resolver(urls)
|
||||
try:
|
||||
match = resolver.resolve(proxy_url)
|
||||
resolver.resolve(proxy_url)
|
||||
except TypeError:
|
||||
self.fail('Failed to coerce lazy object to text')
|
||||
|
||||
|
@ -290,7 +290,7 @@ class ReverseLazyTest(TestCase):
|
|||
self.assertRedirects(response, "/redirected_to/", status_code=301)
|
||||
|
||||
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/')
|
||||
self.assertRedirects(response, "/login/?next=/login_required_view/", status_code=302)
|
||||
self.client.login(username='alfred', password='testpw')
|
||||
|
|
|
@ -148,8 +148,6 @@ class MergeDictTests(IgnorePendingDeprecationWarningsMixin, SimpleTestCase):
|
|||
d3 = {'chris3':'cool3', 'camri3':'cute3', 'cotton3':'adorable3',
|
||||
'tulip3':'snuggable3'}
|
||||
|
||||
d4 = {'twoofme': 'secondone'}
|
||||
|
||||
md = MergeDict(d1, d2, d3)
|
||||
|
||||
self.assertEqual(md['chris'], 'cool')
|
||||
|
|
|
@ -73,7 +73,7 @@ class DecoratorFromMiddlewareTests(TestCase):
|
|||
return HttpResponse(t.render(Context({})))
|
||||
|
||||
request = self.rf.get('/')
|
||||
response = normal_view(request)
|
||||
normal_view(request)
|
||||
self.assertTrue(getattr(request, 'process_request_reached', False))
|
||||
self.assertTrue(getattr(request, 'process_view_reached', False))
|
||||
# process_template_response must not be called for HttpResponse
|
||||
|
|
|
@ -69,7 +69,7 @@ class TestUtilsSimpleLazyObject(TestCase):
|
|||
self.assertEqual(empty, x._wrapped)
|
||||
|
||||
# Second, for an evaluated SimpleLazyObject
|
||||
name = x.name # evaluate
|
||||
x.name # evaluate
|
||||
self.assertIsInstance(x._wrapped, _ComplexObject)
|
||||
# __repr__ contains __repr__ of wrapped object
|
||||
self.assertEqual("<SimpleLazyObject: %r>" % x._wrapped, repr(x))
|
||||
|
@ -99,7 +99,7 @@ class TestUtilsSimpleLazyObject(TestCase):
|
|||
self.assertEqual(s2, complex_object())
|
||||
|
||||
# Second, for an evaluated SimpleLazyObject
|
||||
name = s.name # evaluate
|
||||
s.name # evaluate
|
||||
self.assertIsNot(s._wrapped, empty)
|
||||
s3 = copy.deepcopy(s)
|
||||
self.assertEqual(s3, complex_object())
|
||||
|
@ -186,15 +186,15 @@ class TestUtilsSimpleLazyObjectDjangoTestCase(DjangoTestCase):
|
|||
|
||||
# This would fail with "TypeError: can't pickle instancemethod objects",
|
||||
# only on Python 2.X.
|
||||
pickled = pickle.dumps(x)
|
||||
pickle.dumps(x)
|
||||
|
||||
# Try the variant protocol levels.
|
||||
pickled = pickle.dumps(x, 0)
|
||||
pickled = pickle.dumps(x, 1)
|
||||
pickled = pickle.dumps(x, 2)
|
||||
pickle.dumps(x, 0)
|
||||
pickle.dumps(x, 1)
|
||||
pickle.dumps(x, 2)
|
||||
|
||||
if six.PY2:
|
||||
import cPickle
|
||||
|
||||
# This would fail with "TypeError: expected string or Unicode object, NoneType found".
|
||||
pickled = cPickle.dumps(x)
|
||||
cPickle.dumps(x)
|
||||
|
|
|
@ -77,7 +77,7 @@ class PerformUniqueChecksTest(TestCase):
|
|||
mtv.full_clean()
|
||||
|
||||
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))
|
||||
|
||||
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.']})
|
||||
|
||||
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))
|
||||
|
||||
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.")
|
||||
|
||||
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)
|
||||
with self.assertRaises(ValidationError) as cm:
|
||||
m.full_clean()
|
||||
|
|
|
@ -171,8 +171,8 @@ def non_sensitive_view(request):
|
|||
# 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
|
||||
# is displayed in the exception report.
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
try:
|
||||
raise Exception
|
||||
except Exception:
|
||||
|
@ -186,8 +186,8 @@ def sensitive_view(request):
|
|||
# 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
|
||||
# is displayed in the exception report.
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
try:
|
||||
raise Exception
|
||||
except Exception:
|
||||
|
@ -201,8 +201,8 @@ def paranoid_view(request):
|
|||
# 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
|
||||
# is displayed in the exception report.
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
try:
|
||||
raise 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
|
||||
# so that the tests don't return false positives when the function's 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
|
||||
raise Exception
|
||||
|
||||
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
|
||||
# so that the tests don't return false positives when the function's 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
|
||||
raise Exception
|
||||
|
||||
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
|
||||
# so that the tests don't return false positives when the function's source
|
||||
# is displayed in the exception report.
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
request.exception_reporter_filter = UnsafeExceptionReporterFilter()
|
||||
try:
|
||||
raise Exception
|
||||
|
@ -278,8 +278,8 @@ class Klass(object):
|
|||
# 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 is displayed in the exception report.
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
try:
|
||||
raise Exception
|
||||
except Exception:
|
||||
|
@ -294,8 +294,8 @@ def sensitive_method_view(request):
|
|||
@sensitive_variables('sauce')
|
||||
@sensitive_post_parameters('bacon-key', 'sausage-key')
|
||||
def multivalue_dict_key_error(request):
|
||||
cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])
|
||||
sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])
|
||||
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']) # NOQA
|
||||
try:
|
||||
request.POST['bar']
|
||||
except Exception:
|
||||
|
|
Loading…
Reference in New Issue