1
0
mirror of https://github.com/django/django.git synced 2025-10-31 09:41:08 +00:00

Merge branch 'master' of github.com:django/django into schema-alteration

Conflicts:
	django/db/backends/postgresql_psycopg2/base.py
This commit is contained in:
Andrew Godwin
2012-07-26 18:58:10 +01:00
406 changed files with 4421 additions and 2766 deletions

View File

@@ -565,3 +565,23 @@ class BaseAggregateTestCase(TestCase):
(Decimal('82.8'), 1),
]
)
def test_dates_with_aggregation(self):
"""
Test that .dates() returns a distinct set of dates when applied to a
QuerySet with aggregation.
Refs #18056. Previously, .dates() would return distinct (date_kind,
aggregation) sets, in this case (year, num_authors), so 2008 would be
returned twice because there are books from 2008 with a different
number of authors.
"""
dates = Book.objects.annotate(num_authors=Count("authors")).dates('pubdate', 'year')
self.assertQuerysetEqual(
dates, [
"datetime.datetime(1991, 1, 1, 0, 0)",
"datetime.datetime(1995, 1, 1, 0, 0)",
"datetime.datetime(2007, 1, 1, 0, 0)",
"datetime.datetime(2008, 1, 1, 0, 0)"
]
)

View File

@@ -5,6 +5,7 @@ from datetime import datetime
from django.core.exceptions import ObjectDoesNotExist
from django.db.models.fields import Field, FieldDoesNotExist
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from django.utils.six import PY3
from django.utils.translation import ugettext_lazy
from .models import Article
@@ -321,17 +322,18 @@ class ModelTest(TestCase):
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# Slicing works with longs.
self.assertEqual(Article.objects.all()[0L], a)
self.assertQuerysetEqual(Article.objects.all()[1L:3L],
["<Article: Second article>", "<Article: Third article>"])
self.assertQuerysetEqual((s1 | s2 | s3)[::2L],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# Slicing works with longs (Python 2 only -- Python 3 doesn't have longs).
if not PY3:
self.assertEqual(Article.objects.all()[long(0)], a)
self.assertQuerysetEqual(Article.objects.all()[long(1):long(3)],
["<Article: Second article>", "<Article: Third article>"])
self.assertQuerysetEqual((s1 | s2 | s3)[::long(2)],
["<Article: Area man programs in Python>",
"<Article: Third article>"])
# And can be mixed with ints.
self.assertQuerysetEqual(Article.objects.all()[1:3L],
["<Article: Second article>", "<Article: Third article>"])
# And can be mixed with ints.
self.assertQuerysetEqual(Article.objects.all()[1:long(3)],
["<Article: Second article>", "<Article: Third article>"])
# Slices (without step) are lazy:
self.assertQuerysetEqual(Article.objects.all()[0:5].filter(),

View File

@@ -2,6 +2,7 @@ from __future__ import absolute_import
from django.core.exceptions import FieldError
from django.test import TestCase
from django.utils import six
from .models import Author, Article
@@ -22,13 +23,13 @@ class CustomColumnsTests(TestCase):
Author.objects.all(), [
"Peter Jones", "John Smith",
],
unicode
six.text_type
)
self.assertQuerysetEqual(
Author.objects.filter(first_name__exact="John"), [
"John Smith",
],
unicode
six.text_type
)
self.assertEqual(
Author.objects.get(first_name__exact="John"),
@@ -55,7 +56,7 @@ class CustomColumnsTests(TestCase):
"Peter Jones",
"John Smith",
],
unicode
six.text_type
)
# Get the articles for an author
self.assertQuerysetEqual(
@@ -69,5 +70,5 @@ class CustomColumnsTests(TestCase):
art.authors.filter(last_name='Jones'), [
"Peter Jones"
],
unicode
six.text_type
)

View File

@@ -1,6 +1,7 @@
from __future__ import absolute_import
from django.test import TestCase
from django.utils import six
from .models import Person, Book, Car, PersonManager, PublishedBookManager
@@ -14,7 +15,7 @@ class CustomManagerTests(TestCase):
Person.objects.get_fun_people(), [
"Bugs Bunny"
],
unicode
six.text_type
)
# The RelatedManager used on the 'books' descriptor extends the default
# manager

View File

@@ -2,6 +2,7 @@ import random
import string
from django.db import models
from django.utils import six
class MyWrapper(object):
@@ -44,12 +45,12 @@ class MyAutoField(models.CharField):
if not value:
return
if isinstance(value, MyWrapper):
return unicode(value)
return six.text_type(value)
return value
def get_db_prep_value(self, value, connection, prepared=False):
if not value:
return
if isinstance(value, MyWrapper):
return unicode(value)
return six.text_type(value)
return value

View File

@@ -3,6 +3,7 @@ from __future__ import absolute_import, unicode_literals
from django.db import transaction, IntegrityError
from django.test import TestCase, skipIfDBFeature
from django.utils import six
from .models import Employee, Business, Bar, Foo
@@ -16,7 +17,7 @@ class CustomPKTests(TestCase):
Employee.objects.all(), [
"Dan Jones",
],
unicode
six.text_type
)
fran = Employee.objects.create(
@@ -27,7 +28,7 @@ class CustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
unicode
six.text_type
)
self.assertEqual(Employee.objects.get(pk=123), dan)
@@ -45,7 +46,7 @@ class CustomPKTests(TestCase):
"Fran Bones",
"Dan Jones",
],
unicode
six.text_type
)
# The primary key can be accessed via the pk property on the model.
e = Employee.objects.get(pk=123)
@@ -63,7 +64,7 @@ class CustomPKTests(TestCase):
"Dan Jones",
"Fran Jones",
],
unicode
six.text_type
)
emps = Employee.objects.in_bulk([123, 456])
@@ -76,7 +77,7 @@ class CustomPKTests(TestCase):
"Dan Jones",
"Fran Jones",
],
unicode
six.text_type
)
self.assertQuerysetEqual(
fran.business_set.all(), [
@@ -108,14 +109,14 @@ class CustomPKTests(TestCase):
"Dan Jones",
"Fran Jones",
],
unicode,
six.text_type,
)
self.assertQuerysetEqual(
Employee.objects.filter(business__pk="Sears"), [
"Dan Jones",
"Fran Jones",
],
unicode,
six.text_type,
)
self.assertQuerysetEqual(

View File

@@ -1,6 +1,6 @@
from __future__ import absolute_import
from django.db.models.query_utils import DeferredAttribute
from django.db.models.query_utils import DeferredAttribute, InvalidQuery
from django.test import TestCase
from .models import Secondary, Primary, Child, BigChild, ChildProxy
@@ -73,9 +73,19 @@ class DeferTests(TestCase):
self.assert_delayed(qs.defer("name").get(pk=p1.pk), 1)
self.assert_delayed(qs.only("name").get(pk=p1.pk), 2)
# DOES THIS WORK?
self.assert_delayed(qs.only("name").select_related("related")[0], 1)
self.assert_delayed(qs.defer("related").select_related("related")[0], 0)
# When we defer a field and also select_related it, the query is
# invalid and raises an exception.
with self.assertRaises(InvalidQuery):
qs.only("name").select_related("related")[0]
with self.assertRaises(InvalidQuery):
qs.defer("related").select_related("related")[0]
# With a depth-based select_related, all deferred ForeignKeys are
# deferred instead of traversed.
with self.assertNumQueries(3):
obj = qs.defer("related").select_related()[0]
self.assert_delayed(obj, 1)
self.assertEqual(obj.related.id, s1.pk)
# Saving models with deferred fields is possible (but inefficient,
# since every field has to be retrieved first).
@@ -155,7 +165,7 @@ class DeferTests(TestCase):
children = ChildProxy.objects.all().select_related().only('id', 'name')
self.assertEqual(len(children), 1)
child = children[0]
self.assert_delayed(child, 1)
self.assert_delayed(child, 2)
self.assertEqual(child.name, 'p1')
self.assertEqual(child.value, 'xx')

View File

@@ -2,6 +2,7 @@ from __future__ import absolute_import
from django.db import models, IntegrityError
from django.test import TestCase, skipUnlessDBFeature, skipIfDBFeature
from django.utils.six.moves import xrange
from .models import (R, RChild, S, T, U, A, M, MR, MRNull,
create_a, get_default_r, User, Avatar, HiddenUser, HiddenUserProfile)

View File

@@ -3,6 +3,7 @@ from __future__ import absolute_import, unicode_literals
from django.core.exceptions import FieldError
from django.db.models import F
from django.test import TestCase
from django.utils import six
from .models import Company, Employee
@@ -156,7 +157,7 @@ class ExpressionsTests(TestCase):
"Frank Meyer",
"Max Mustermann",
],
lambda c: unicode(c.point_of_contact),
lambda c: six.text_type(c.point_of_contact),
)
c = Company.objects.all()[0]

View File

@@ -3,6 +3,7 @@ from __future__ import absolute_import
from datetime import datetime
from django.test import TestCase
from django.utils import six
from .models import Article
@@ -13,6 +14,6 @@ class DefaultTests(TestCase):
now = datetime.now()
a.save()
self.assertTrue(isinstance(a.id, (int, long)))
self.assertTrue(isinstance(a.id, six.integer_types))
self.assertEqual(a.headline, "Default headline")
self.assertTrue((now - a.pub_date).seconds < 5)

View File

@@ -4,6 +4,7 @@ import json
from django.db import models
from django.utils.encoding import force_unicode
from django.utils import six
class Small(object):
@@ -18,7 +19,7 @@ class Small(object):
return '%s%s' % (force_unicode(self.first), force_unicode(self.second))
def __str__(self):
return unicode(self).encode('utf-8')
return six.text_type(self).encode('utf-8')
class SmallField(models.Field):
"""
@@ -41,7 +42,7 @@ class SmallField(models.Field):
return Small(value[0], value[1])
def get_db_prep_save(self, value, connection):
return unicode(value)
return six.text_type(value)
def get_prep_lookup(self, lookup_type, value):
if lookup_type == 'exact':
@@ -66,7 +67,7 @@ class JSONField(models.TextField):
if not value:
return None
if isinstance(value, basestring):
if isinstance(value, six.string_types):
value = json.loads(value)
return value

View File

@@ -26,5 +26,5 @@ class Storage(models.Model):
normal = models.FileField(storage=temp_storage, upload_to='tests')
custom = models.FileField(storage=temp_storage, upload_to=custom_upload_to)
random = models.FileField(storage=temp_storage, upload_to=random_upload_to)
random = models.FileField(storage=temp_storage, upload_to=random_upload_to, max_length=16)
default = models.FileField(storage=temp_storage, upload_to='tests', default='tests/default.txt')

View File

@@ -5,6 +5,7 @@ import shutil
import tempfile
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.files import File
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import SimpleUploadedFile
@@ -102,11 +103,23 @@ class FileStorageTests(TestCase):
obj4.random.save("random_file", ContentFile(b"random content"))
self.assertTrue(obj4.random.name.endswith("/random_file"))
# Clean up the temporary files and dir.
obj1.normal.delete()
obj2.normal.delete()
obj3.default.delete()
obj4.random.delete()
def test_max_length(self):
"""
Test that FileField validates the length of the generated file name
that will be stored in the database. Regression for #9893.
"""
# upload_to = 'unused', so file names are saved as '456/xxxxx'.
# max_length = 16, so names longer than 12 characters are rejected.
s1 = Storage(random=SimpleUploadedFile(12 * 'x', b"content"))
s1.full_clean()
with self.assertRaises(ValidationError):
Storage(random=SimpleUploadedFile(13 * 'x', b"content")).full_clean()
# Ticket #18515: validation for an already saved file should not check
# against a regenerated file name (and potentially raise a ValidationError
# if max_length is exceeded
s1.save()
s1.full_clean()
class FileTests(unittest.TestCase):

View File

@@ -40,7 +40,7 @@ class TestNoInitialDataLoading(TransactionTestCase):
# Test presence of fixture (flush called by TransactionTestCase)
self.assertQuerysetEqual(
Book.objects.all(), [
u'Achieving self-awareness of Python programs'
'Achieving self-awareness of Python programs'
],
lambda a: a.name
)

View File

@@ -231,7 +231,7 @@ class GenericRelationsTests(TestCase):
tag = TaggedItem.objects.create(content_object=tailless, tag="lizard")
self.assertEqual(tag.content_object, tailless)
class CustomWidget(forms.CharField):
class CustomWidget(forms.TextInput):
pass
class TaggedItemForm(forms.ModelForm):

View File

@@ -7,6 +7,7 @@ This demonstrates features of the database API.
from __future__ import unicode_literals
from django.db import models
from django.utils import six
class Author(models.Model):
@@ -35,7 +36,7 @@ class Season(models.Model):
gt = models.IntegerField(null=True, blank=True)
def __unicode__(self):
return unicode(self.year)
return six.text_type(self.year)
class Game(models.Model):
season = models.ForeignKey(Season, related_name='games')

View File

@@ -6,6 +6,7 @@ Make sure to set ``related_name`` if you use relationships to the same table.
from __future__ import unicode_literals
from django.db import models
from django.utils import six
class User(models.Model):
@@ -17,7 +18,7 @@ class Issue(models.Model):
client = models.ForeignKey(User, related_name='test_issue_client')
def __unicode__(self):
return unicode(self.num)
return six.text_type(self.num)
class Meta:
ordering = ('num',)

View File

@@ -3,6 +3,7 @@ from __future__ import absolute_import
from datetime import datetime
from django.test import TestCase
from django.utils import six
from .models import Reporter, Article, Writer
@@ -24,7 +25,7 @@ class M2MIntermediaryTests(TestCase):
("John Smith", "Main writer"),
("Jane Doe", "Contributor"),
],
lambda w: (unicode(w.reporter), w.position)
lambda w: (six.text_type(w.reporter), w.position)
)
self.assertEqual(w1.reporter, r1)
self.assertEqual(w2.reporter, r2)
@@ -36,5 +37,5 @@ class M2MIntermediaryTests(TestCase):
r1.writer_set.all(), [
("John Smith", "Main writer")
],
lambda w: (unicode(w.reporter), w.position)
lambda w: (six.text_type(w.reporter), w.position)
)

View File

@@ -3,8 +3,9 @@ from __future__ import absolute_import
from copy import deepcopy
from datetime import datetime
from django.core.exceptions import MultipleObjectsReturned
from django.core.exceptions import MultipleObjectsReturned, FieldError
from django.test import TestCase
from django.utils import six
from django.utils.translation import ugettext_lazy
from .models import Article, Reporter
@@ -421,6 +422,18 @@ class ManyToOneTests(TestCase):
lazy = ugettext_lazy('test')
reporter.article_set.create(headline=lazy,
pub_date=datetime(2011, 6, 10))
notlazy = unicode(lazy)
notlazy = six.text_type(lazy)
article = reporter.article_set.get()
self.assertEqual(article.headline, notlazy)
def test_values_list_exception(self):
expected_message = "Cannot resolve keyword 'notafield' into field. Choices are: %s"
self.assertRaisesMessage(FieldError,
expected_message % ', '.join(Reporter._meta.get_all_field_names()),
Article.objects.values_list,
'reporter__notafield')
self.assertRaisesMessage(FieldError,
expected_message % ', '.join(['EXTRA',] + Article._meta.get_all_field_names()),
Article.objects.extra(select={'EXTRA': 'EXTRA_SELECT'}).values_list,
'notafield')

View File

@@ -88,8 +88,8 @@ class ManyToOneNullTests(TestCase):
def test_clear_efficiency(self):
r = Reporter.objects.create()
for _ in xrange(3):
for _ in range(3):
r.article_set.create()
with self.assertNumQueries(1):
r.article_set.clear()
self.assertEqual(r.article_set.count(), 0)
self.assertEqual(r.article_set.count(), 0)

View File

@@ -13,6 +13,7 @@ import tempfile
from django.core.files.storage import FileSystemStorage
from django.db import models
from django.utils import six
temp_storage_dir = tempfile.mkdtemp(dir=os.environ['DJANGO_TEST_TEMP_DIR'])
@@ -226,7 +227,7 @@ class BigInt(models.Model):
biggie = models.BigIntegerField()
def __unicode__(self):
return unicode(self.biggie)
return six.text_type(self.biggie)
class MarkupField(models.CharField):
def __init__(self, *args, **kwargs):

View File

@@ -11,6 +11,7 @@ from django.db import connection
from django.forms.models import model_to_dict
from django.utils.unittest import skipUnless
from django.test import TestCase
from django.utils import six
from .models import (Article, ArticleStatus, BetterWriter, BigInt, Book,
Category, CommaSeparatedInteger, CustomFieldForExclusionModel, DerivedBook,
@@ -653,7 +654,7 @@ class OldFormForXTests(TestCase):
# ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
# fields with the 'choices' attribute are represented by a ChoiceField.
f = ArticleForm(auto_id=False)
self.assertHTMLEqual(unicode(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
self.assertHTMLEqual(six.text_type(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
<tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" /></td></tr>
<tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
<tr><th>Writer:</th><td><select name="writer">
@@ -681,14 +682,14 @@ class OldFormForXTests(TestCase):
# a value of None. If a field isn't specified on a form, the object created
# from the form can't provide a value for that field!
f = PartialArticleForm(auto_id=False)
self.assertHTMLEqual(unicode(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
self.assertHTMLEqual(six.text_type(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
<tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>''')
# When the ModelForm is passed an instance, that instance's current values are
# inserted as 'initial' data in each Field.
w = Writer.objects.get(name='Mike Royko')
f = RoykoForm(auto_id=False, instance=w)
self.assertHTMLEqual(unicode(f), '''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" /><br /><span class="helptext">Use both first and last names.</span></td></tr>''')
self.assertHTMLEqual(six.text_type(f), '''<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" /><br /><span class="helptext">Use both first and last names.</span></td></tr>''')
art = Article(
headline='Test article',
@@ -725,7 +726,7 @@ class OldFormForXTests(TestCase):
'headline': 'Test headline',
'slug': 'test-headline',
'pub_date': '1984-02-06',
'writer': unicode(w_royko.pk),
'writer': six.text_type(w_royko.pk),
'article': 'Hello.'
}, instance=art)
self.assertEqual(f.errors, {})
@@ -808,9 +809,9 @@ class OldFormForXTests(TestCase):
'headline': 'New headline',
'slug': 'new-headline',
'pub_date': '1988-01-04',
'writer': unicode(w_royko.pk),
'writer': six.text_type(w_royko.pk),
'article': 'Hello.',
'categories': [unicode(c1.id), unicode(c2.id)]
'categories': [six.text_type(c1.id), six.text_type(c2.id)]
}, instance=new_art)
new_art = f.save()
self.assertEqual(new_art.id == art_id_1, True)
@@ -820,7 +821,7 @@ class OldFormForXTests(TestCase):
# Now, submit form data with no categories. This deletes the existing categories.
f = TestArticleForm({'headline': 'New headline', 'slug': 'new-headline', 'pub_date': '1988-01-04',
'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=new_art)
'writer': six.text_type(w_royko.pk), 'article': 'Hello.'}, instance=new_art)
new_art = f.save()
self.assertEqual(new_art.id == art_id_1, True)
new_art = Article.objects.get(id=art_id_1)
@@ -828,7 +829,7 @@ class OldFormForXTests(TestCase):
# Create a new article, with categories, via the form.
f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01',
'writer': unicode(w_royko.pk), 'article': 'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
'writer': six.text_type(w_royko.pk), 'article': 'Test.', 'categories': [six.text_type(c1.id), six.text_type(c2.id)]})
new_art = f.save()
art_id_2 = new_art.id
self.assertEqual(art_id_2 not in (None, art_id_1), True)
@@ -837,7 +838,7 @@ class OldFormForXTests(TestCase):
# Create a new article, with no categories, via the form.
f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01',
'writer': unicode(w_royko.pk), 'article': 'Test.'})
'writer': six.text_type(w_royko.pk), 'article': 'Test.'})
new_art = f.save()
art_id_3 = new_art.id
self.assertEqual(art_id_3 not in (None, art_id_1, art_id_2), True)
@@ -847,7 +848,7 @@ class OldFormForXTests(TestCase):
# Create a new article, with categories, via the form, but use commit=False.
# The m2m data won't be saved until save_m2m() is invoked on the form.
f = ArticleForm({'headline': 'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': '1967-11-01',
'writer': unicode(w_royko.pk), 'article': 'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
'writer': six.text_type(w_royko.pk), 'article': 'Test.', 'categories': [six.text_type(c1.id), six.text_type(c2.id)]})
new_art = f.save(commit=False)
# Manually save the instance
@@ -1091,12 +1092,12 @@ class OldFormForXTests(TestCase):
<p><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>''' % (w_woodward.pk, w_bernstein.pk, bw.pk, w_royko.pk))
data = {
'writer': unicode(w_woodward.pk),
'writer': six.text_type(w_woodward.pk),
'age': '65',
}
form = WriterProfileForm(data)
instance = form.save()
self.assertEqual(unicode(instance), 'Bob Woodward is 65')
self.assertEqual(six.text_type(instance), 'Bob Woodward is 65')
form = WriterProfileForm(instance=instance)
self.assertHTMLEqual(form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
@@ -1376,7 +1377,7 @@ class OldFormForXTests(TestCase):
# Similar to a regular Form class you can define custom media to be used on
# the ModelForm.
f = ModelFormWithMedia()
self.assertHTMLEqual(unicode(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
self.assertHTMLEqual(six.text_type(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="/some/form/javascript"></script>''')
f = CommaSeparatedIntegerForm({'field': '1,2,3'})
@@ -1445,7 +1446,7 @@ class OldFormForXTests(TestCase):
(22, 'Pear')))
form = InventoryForm(instance=core)
self.assertHTMLEqual(unicode(form['parent']), '''<select name="parent" id="id_parent">
self.assertHTMLEqual(six.text_type(form['parent']), '''<select name="parent" id="id_parent">
<option value="">---------</option>
<option value="86" selected="selected">Apple</option>
<option value="87">Core</option>
@@ -1466,7 +1467,7 @@ class OldFormForXTests(TestCase):
self.assertEqual(CategoryForm.base_fields.keys(),
['description', 'url'])
self.assertHTMLEqual(unicode(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr>
self.assertHTMLEqual(six.text_type(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr>
<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>''')
# to_field_name should also work on ModelMultipleChoiceField ##################
@@ -1481,5 +1482,5 @@ class OldFormForXTests(TestCase):
def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self):
self.assertEqual(CustomFieldForExclusionForm.base_fields.keys(), ['name'])
self.assertHTMLEqual(unicode(CustomFieldForExclusionForm()),
self.assertHTMLEqual(six.text_type(CustomFieldForExclusionForm()),
'''<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="10" /></td></tr>''')

View File

@@ -3,6 +3,7 @@ from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils import six
class Author(models.Model):
@@ -149,7 +150,7 @@ class Revision(models.Model):
unique_together = (("repository", "revision"),)
def __unicode__(self):
return "%s (%s)" % (self.revision, unicode(self.repository))
return "%s (%s)" % (self.revision, six.text_type(self.repository))
# models for testing callable defaults (see bug #7975). If you define a model
# with a callable default value, you cannot rely on the initial value in a

View File

@@ -10,6 +10,7 @@ from django.db import models
from django.forms.models import (_get_foreign_key, inlineformset_factory,
modelformset_factory)
from django.test import TestCase, skipUnlessDBFeature
from django.utils import six
from .models import (Author, BetterAuthor, Book, BookWithCustomPK,
BookWithOptionalAltEditor, AlternateBook, AuthorMeeting, CustomPrimaryKey,
@@ -72,7 +73,7 @@ class DeletionTests(TestCase):
'form-TOTAL_FORMS': '1',
'form-INITIAL_FORMS': '1',
'form-MAX_NUM_FORMS': '0',
'form-0-id': unicode(poet.id),
'form-0-id': six.text_type(poet.id),
'form-0-name': 'x' * 1000,
}
formset = PoetFormSet(data, queryset=Poet.objects.all())
@@ -772,7 +773,7 @@ class ModelFormsetTest(TestCase):
'owner_set-TOTAL_FORMS': '3',
'owner_set-INITIAL_FORMS': '1',
'owner_set-MAX_NUM_FORMS': '',
'owner_set-0-auto_id': unicode(owner1.auto_id),
'owner_set-0-auto_id': six.text_type(owner1.auto_id),
'owner_set-0-name': 'Joe Perry',
'owner_set-1-auto_id': '',
'owner_set-1-name': 'Jack Berry',
@@ -835,7 +836,7 @@ class ModelFormsetTest(TestCase):
'ownerprofile-TOTAL_FORMS': '1',
'ownerprofile-INITIAL_FORMS': '1',
'ownerprofile-MAX_NUM_FORMS': '1',
'ownerprofile-0-owner': unicode(owner1.auto_id),
'ownerprofile-0-owner': six.text_type(owner1.auto_id),
'ownerprofile-0-age': '55',
}
formset = FormSet(data, instance=owner1)
@@ -993,8 +994,8 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
'membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')),
'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-karma': '',
}
formset = FormSet(data, instance=person)
@@ -1007,8 +1008,8 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
'membership_set-0-date_joined': unicode(one_day_later.strftime('%Y-%m-%d %H:%M:%S')),
'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-date_joined': six.text_type(one_day_later.strftime('%Y-%m-%d %H:%M:%S')),
'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-karma': '',
}
formset = FormSet(filled_data, instance=person)
@@ -1029,9 +1030,9 @@ class ModelFormsetTest(TestCase):
'membership_set-TOTAL_FORMS': '1',
'membership_set-INITIAL_FORMS': '0',
'membership_set-MAX_NUM_FORMS': '',
'membership_set-0-date_joined_0': unicode(now.strftime('%Y-%m-%d')),
'membership_set-0-date_joined_1': unicode(now.strftime('%H:%M:%S')),
'initial-membership_set-0-date_joined': unicode(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-date_joined_0': six.text_type(now.strftime('%Y-%m-%d')),
'membership_set-0-date_joined_1': six.text_type(now.strftime('%H:%M:%S')),
'initial-membership_set-0-date_joined': six.text_type(now.strftime('%Y-%m-%d %H:%M:%S')),
'membership_set-0-karma': '',
}
formset = FormSet(data, instance=person)

View File

@@ -4,6 +4,7 @@ from operator import attrgetter
from django.core.exceptions import FieldError
from django.test import TestCase
from django.utils import six
from .models import (Chef, CommonInfo, ItalianRestaurant, ParkingLot, Place,
Post, Restaurant, Student, StudentWorker, Supplier, Worker, MixinModel)
@@ -21,8 +22,8 @@ class ModelInheritanceTests(TestCase):
s = Student.objects.create(name="Pebbles", age=5, school_class="1B")
self.assertEqual(unicode(w1), "Worker Fred")
self.assertEqual(unicode(s), "Student Pebbles")
self.assertEqual(six.text_type(w1), "Worker Fred")
self.assertEqual(six.text_type(s), "Student Pebbles")
# The children inherit the Meta class of their parents (if they don't
# specify their own).

View File

@@ -3,6 +3,7 @@ Tests for the order_with_respect_to Meta attribute.
"""
from django.db import models
from django.utils import six
class Question(models.Model):
@@ -16,7 +17,7 @@ class Answer(models.Model):
order_with_respect_to = 'question'
def __unicode__(self):
return unicode(self.text)
return six.text_type(self.text)
class Post(models.Model):
title = models.CharField(max_length=200)

View File

@@ -4,6 +4,7 @@ from datetime import datetime
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.test import TestCase
from django.utils import six
from .models import Article
@@ -32,7 +33,7 @@ class PaginationTests(TestCase):
def test_first_page(self):
paginator = Paginator(Article.objects.all(), 5)
p = paginator.page(1)
self.assertEqual("<Page 1 of 2>", unicode(p))
self.assertEqual("<Page 1 of 2>", six.text_type(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 1>",
"<Article: Article 2>",
@@ -52,7 +53,7 @@ class PaginationTests(TestCase):
def test_last_page(self):
paginator = Paginator(Article.objects.all(), 5)
p = paginator.page(2)
self.assertEqual("<Page 2 of 2>", unicode(p))
self.assertEqual("<Page 2 of 2>", six.text_type(p))
self.assertQuerysetEqual(p.object_list, [
"<Article: Article 6>",
"<Article: Article 7>",
@@ -109,7 +110,7 @@ class PaginationTests(TestCase):
self.assertEqual(3, paginator.num_pages)
self.assertEqual([1, 2, 3], paginator.page_range)
p = paginator.page(2)
self.assertEqual("<Page 2 of 3>", unicode(p))
self.assertEqual("<Page 2 of 3>", six.text_type(p))
self.assertEqual([4, 5, 6], p.object_list)
self.assertTrue(p.has_next())
self.assertTrue(p.has_previous())

View File

@@ -4,6 +4,7 @@ from django.contrib.contenttypes.models import ContentType
from django.db import connection
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from .models import (Author, Book, Reader, Qualification, Teacher, Department,
TaggedItem, Bookmark, AuthorAddress, FavoriteAuthors, AuthorWithAge,
@@ -120,7 +121,7 @@ class PrefetchRelatedTests(TestCase):
"""
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by')
lists = [[[unicode(r) for r in b.read_by.all()]
lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists,
@@ -134,7 +135,7 @@ class PrefetchRelatedTests(TestCase):
def test_overriding_prefetch(self):
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books', 'books__read_by')
lists = [[[unicode(r) for r in b.read_by.all()]
lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists,
@@ -146,7 +147,7 @@ class PrefetchRelatedTests(TestCase):
])
with self.assertNumQueries(3):
qs = Author.objects.prefetch_related('books__read_by', 'books')
lists = [[[unicode(r) for r in b.read_by.all()]
lists = [[[six.text_type(r) for r in b.read_by.all()]
for b in a.books.all()]
for a in qs]
self.assertEqual(lists,
@@ -164,7 +165,7 @@ class PrefetchRelatedTests(TestCase):
# Need a double
with self.assertNumQueries(3):
author = Author.objects.prefetch_related('books__read_by').get(name="Charlotte")
lists = [[unicode(r) for r in b.read_by.all()]
lists = [[six.text_type(r) for r in b.read_by.all()]
for b in author.books.all()]
self.assertEqual(lists, [["Amy"], ["Belinda"]]) # Poems, Jane Eyre
@@ -175,7 +176,7 @@ class PrefetchRelatedTests(TestCase):
"""
with self.assertNumQueries(2):
qs = Author.objects.select_related('first_book').prefetch_related('first_book__read_by')
lists = [[unicode(r) for r in a.first_book.read_by.all()]
lists = [[six.text_type(r) for r in a.first_book.read_by.all()]
for a in qs]
self.assertEqual(lists, [["Amy"],
["Amy"],
@@ -227,7 +228,7 @@ class DefaultManagerTests(TestCase):
# qualifications, since this will do one query per teacher.
qs = Department.objects.prefetch_related('teachers')
depts = "".join(["%s department: %s\n" %
(dept.name, ", ".join(unicode(t) for t in dept.teachers.all()))
(dept.name, ", ".join(six.text_type(t) for t in dept.teachers.all()))
for dept in qs])
self.assertEqual(depts,
@@ -343,9 +344,9 @@ class MultiTableInheritanceTest(TestCase):
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = AuthorWithAge.objects.prefetch_related('addresses')
addresses = [[unicode(address) for address in obj.addresses.all()]
addresses = [[six.text_type(address) for address in obj.addresses.all()]
for obj in qs]
self.assertEqual(addresses, [[unicode(self.authorAddress)], [], []])
self.assertEqual(addresses, [[six.text_type(self.authorAddress)], [], []])
def test_foreignkey_to_inherited(self):
with self.assertNumQueries(2):
@@ -356,19 +357,19 @@ class MultiTableInheritanceTest(TestCase):
def test_m2m_to_inheriting_model(self):
qs = AuthorWithAge.objects.prefetch_related('books_with_year')
with self.assertNumQueries(2):
lst = [[unicode(book) for book in author.books_with_year.all()]
lst = [[six.text_type(book) for book in author.books_with_year.all()]
for author in qs]
qs = AuthorWithAge.objects.all()
lst2 = [[unicode(book) for book in author.books_with_year.all()]
lst2 = [[six.text_type(book) for book in author.books_with_year.all()]
for author in qs]
self.assertEqual(lst, lst2)
qs = BookWithYear.objects.prefetch_related('aged_authors')
with self.assertNumQueries(2):
lst = [[unicode(author) for author in book.aged_authors.all()]
lst = [[six.text_type(author) for author in book.aged_authors.all()]
for book in qs]
qs = BookWithYear.objects.all()
lst2 = [[unicode(author) for author in book.aged_authors.all()]
lst2 = [[six.text_type(author) for author in book.aged_authors.all()]
for book in qs]
self.assertEqual(lst, lst2)
@@ -410,23 +411,23 @@ class ForeignKeyToFieldTest(TestCase):
def test_foreignkey(self):
with self.assertNumQueries(2):
qs = Author.objects.prefetch_related('addresses')
addresses = [[unicode(address) for address in obj.addresses.all()]
addresses = [[six.text_type(address) for address in obj.addresses.all()]
for obj in qs]
self.assertEqual(addresses, [[unicode(self.authorAddress)], [], []])
self.assertEqual(addresses, [[six.text_type(self.authorAddress)], [], []])
def test_m2m(self):
with self.assertNumQueries(3):
qs = Author.objects.all().prefetch_related('favorite_authors', 'favors_me')
favorites = [(
[unicode(i_like) for i_like in author.favorite_authors.all()],
[unicode(likes_me) for likes_me in author.favors_me.all()]
[six.text_type(i_like) for i_like in author.favorite_authors.all()],
[six.text_type(likes_me) for likes_me in author.favors_me.all()]
) for author in qs]
self.assertEqual(
favorites,
[
([unicode(self.author2)],[unicode(self.author3)]),
([unicode(self.author3)],[unicode(self.author1)]),
([unicode(self.author1)],[unicode(self.author2)])
([six.text_type(self.author2)],[six.text_type(self.author3)]),
([six.text_type(self.author3)],[six.text_type(self.author1)]),
([six.text_type(self.author1)],[six.text_type(self.author2)])
]
)

View File

@@ -1,6 +1,7 @@
from __future__ import absolute_import
from django.test import TestCase
from django.utils import six
from .models import Person
@@ -19,7 +20,7 @@ class SaveDeleteHookTests(TestCase):
Person.objects.all(), [
"John Smith",
],
unicode
six.text_type
)
p.delete()

View File

@@ -36,6 +36,8 @@ class SelectForUpdateTests(TransactionTestCase):
# issuing a SELECT ... FOR UPDATE will block.
new_connections = ConnectionHandler(settings.DATABASES)
self.new_connection = new_connections[DEFAULT_DB_ALIAS]
self.new_connection.enter_transaction_management()
self.new_connection.managed(True)
# We need to set settings.DEBUG to True so we can capture
# the output SQL to examine.
@@ -48,6 +50,7 @@ class SelectForUpdateTests(TransactionTestCase):
# this in the course of their run.
transaction.managed(False)
transaction.leave_transaction_management()
self.new_connection.leave_transaction_management()
except transaction.TransactionManagementError:
pass
self.new_connection.close()
@@ -66,7 +69,7 @@ class SelectForUpdateTests(TransactionTestCase):
'for_update': self.new_connection.ops.for_update_sql(),
}
self.cursor.execute(sql, ())
result = self.cursor.fetchone()
self.cursor.fetchone()
def end_blocking_transaction(self):
# Roll back the blocking transaction.
@@ -203,7 +206,7 @@ class SelectForUpdateTests(TransactionTestCase):
sanity_count += 1
time.sleep(1)
if sanity_count >= 10:
raise ValueError, 'Thread did not run and block'
raise ValueError('Thread did not run and block')
# Check the person hasn't been updated. Since this isn't
# using FOR UPDATE, it won't block.

View File

@@ -10,6 +10,7 @@ from __future__ import unicode_literals
from decimal import Decimal
from django.db import models
from django.utils import six
class Category(models.Model):
@@ -100,7 +101,7 @@ class TeamField(models.CharField):
super(TeamField, self).__init__(max_length=100)
def get_db_prep_save(self, value, connection):
return unicode(value.title)
return six.text_type(value.title)
def to_python(self, value):
if isinstance(value, Team):

View File

@@ -10,6 +10,7 @@ from django.conf import settings
from django.core import serializers
from django.db import transaction, connection
from django.test import TestCase, TransactionTestCase, Approximate
from django.utils import six
from django.utils import unittest
from .models import (Category, Author, Article, AuthorProfile, Actor, Movie,
@@ -295,7 +296,7 @@ class XmlSerializerTestCase(SerializersTestBase, TestCase):
def _comparison_value(value):
# The XML serializer handles everything as strings, so comparisons
# need to be performed on the stringified value
return unicode(value)
return six.text_type(value)
@staticmethod
def _validate_output(serial_str):
@@ -461,7 +462,7 @@ else:
# yaml.safe_load will return non-string objects for some
# of the fields we are interested in, this ensures that
# everything comes back as a string
if isinstance(field_value, basestring):
if isinstance(field_value, six.string_types):
ret_list.append(field_value)
else:
ret_list.append(str(field_value))

View File

@@ -3,6 +3,7 @@ from __future__ import absolute_import
from django.db.models import signals
from django.dispatch import receiver
from django.test import TestCase
from django.utils import six
from .models import Person, Car
@@ -144,7 +145,7 @@ class SignalTests(TestCase):
Person.objects.all(), [
"James Jones",
],
unicode
six.text_type
)
signals.post_delete.disconnect(post_delete_test)

View File

@@ -1,3 +1,7 @@
try:
from urllib.parse import urlencode
except ImportError: # Python 2
from urllib import urlencode
from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required
@@ -9,7 +13,6 @@ from django.shortcuts import render_to_response
from django.template import Context, Template
from django.utils.decorators import method_decorator
def get_view(request):
"A simple view that expects a GET request, and returns a rendered template"
t = Template('This is a test. {{ var }} is the value.', name='GET Template')
@@ -58,7 +61,6 @@ def raw_post_view(request):
def redirect_view(request):
"A view that redirects all requests to the GET view"
if request.GET:
from urllib import urlencode
query = '?' + urlencode(request.GET, True)
else:
query = ''

View File

@@ -4,6 +4,7 @@ updates.
"""
from django.db import models
from django.utils import six
class DataPoint(models.Model):
@@ -12,14 +13,14 @@ class DataPoint(models.Model):
another_value = models.CharField(max_length=20, blank=True)
def __unicode__(self):
return unicode(self.name)
return six.text_type(self.name)
class RelatedPoint(models.Model):
name = models.CharField(max_length=20)
data = models.ForeignKey(DataPoint)
def __unicode__(self):
return unicode(self.name)
return six.text_type(self.name)
class A(models.Model):

View File

@@ -55,6 +55,14 @@ class UpdateOnlyFieldsTests(TestCase):
self.assertEqual(e3.name, 'Ian')
self.assertEqual(e3.profile, profile_receptionist)
with self.assertNumQueries(1):
e3.profile = profile_boss
e3.save(update_fields=['profile_id'])
e4 = Employee.objects.get(pk=e3.pk)
self.assertEqual(e4.profile, profile_boss)
self.assertEqual(e4.profile_id, profile_boss.pk)
def test_update_fields_inheritance_with_proxy_model(self):
profile_boss = Profile.objects.create(name='Boss', salary=3000)
profile_receptionist = Profile.objects.create(name='Receptionist', salary=1000)