Fixed a bunch more tests that were failing in Oracle due to false assumptions about the primary keys of objects.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15789 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Ian Kelly 2011-03-09 23:46:28 +00:00
parent 23103bddb9
commit f17fc56602
12 changed files with 149 additions and 135 deletions

View File

@ -1,3 +1,4 @@
from django.conf import settings
from django.contrib.flatpages.admin import FlatpageForm from django.contrib.flatpages.admin import FlatpageForm
from django.test import TestCase from django.test import TestCase
@ -6,7 +7,7 @@ class FlatpageAdminFormTests(TestCase):
self.form_data = { self.form_data = {
'title': "A test page", 'title': "A test page",
'content': "This is a test", 'content': "This is a test",
'sites': [1], 'sites': [settings.SITE_ID],
} }
def test_flatpage_admin_form_url_validation(self): def test_flatpage_admin_form_url_validation(self):

View File

@ -68,7 +68,7 @@ class FlatpageViewTests(TestCase):
enable_comments=False, enable_comments=False,
registration_required=False, registration_required=False,
) )
fp.sites.add(1) fp.sites.add(settings.SITE_ID)
response = self.client.get('/flatpage_root/some.very_special~chars-here/') response = self.client.get('/flatpage_root/some.very_special~chars-here/')
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)

View File

@ -55,7 +55,7 @@ class CustomField(TestCase):
# Serialization works, too. # Serialization works, too.
stream = serializers.serialize("json", MyModel.objects.all()) stream = serializers.serialize("json", MyModel.objects.all())
self.assertEqual(stream, '[{"pk": 1, "model": "field_subclassing.mymodel", "fields": {"data": "12", "name": "m"}}]') self.assertEqual(stream, '[{"pk": %d, "model": "field_subclassing.mymodel", "fields": {"data": "12", "name": "m"}}]' % m1.pk)
obj = list(serializers.deserialize("json", stream))[0] obj = list(serializers.deserialize("json", stream))[0]
self.assertEqual(obj.object, m) self.assertEqual(obj.object, m)

View File

@ -2,6 +2,7 @@ import StringIO
import sys import sys
from django.conf import settings from django.conf import settings
from django.contrib.sites.models import Site
from django.core import management from django.core import management
from django.db import DEFAULT_DB_ALIAS from django.db import DEFAULT_DB_ALIAS
from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature
@ -45,6 +46,7 @@ class FixtureLoadingTests(TestCase):
def test_loading_and_dumping(self): def test_loading_and_dumping(self):
new_io = StringIO.StringIO() new_io = StringIO.StringIO()
Site.objects.all().delete()
# Load fixture 1. Single JSON file, with two objects. # Load fixture 1. Single JSON file, with two objects.
management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
self.assertQuerysetEqual(Article.objects.all(), [ self.assertQuerysetEqual(Article.objects.all(), [
@ -159,6 +161,7 @@ class FixtureLoadingTests(TestCase):
def test_dumpdata_with_excludes(self): def test_dumpdata_with_excludes(self):
# Load fixture1 which has a site, two articles, and a category # Load fixture1 which has a site, two articles, and a category
Site.objects.all().delete()
management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False)
# Excluding fixtures app should only leave sites # Excluding fixtures app should only leave sites
@ -200,15 +203,15 @@ class FixtureLoadingTests(TestCase):
exclude_list=['fixtures.FooModel']) exclude_list=['fixtures.FooModel'])
def test_dumpdata_with_filtering_manager(self): def test_dumpdata_with_filtering_manager(self):
Spy(name='Paul').save() spy1 = Spy.objects.create(name='Paul')
Spy(name='Alex', cover_blown=True).save() spy2 = Spy.objects.create(name='Alex', cover_blown=True)
self.assertQuerysetEqual(Spy.objects.all(), self.assertQuerysetEqual(Spy.objects.all(),
['<Spy: Paul>']) ['<Spy: Paul>'])
# Use the default manager # Use the default manager
self._dumpdata_assert(['fixtures.Spy'],'[{"pk": 1, "model": "fixtures.spy", "fields": {"cover_blown": false}}]') self._dumpdata_assert(['fixtures.Spy'],'[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % spy1.pk)
# Dump using Django's base manager. Should return all objects, # Dump using Django's base manager. Should return all objects,
# even those normally filtered by the manager # even those normally filtered by the manager
self._dumpdata_assert(['fixtures.Spy'], '[{"pk": 2, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": 1, "model": "fixtures.spy", "fields": {"cover_blown": false}}]', use_base_manager=True) self._dumpdata_assert(['fixtures.Spy'], '[{"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": true}}, {"pk": %d, "model": "fixtures.spy", "fields": {"cover_blown": false}}]' % (spy2.pk, spy1.pk), use_base_manager=True)
def test_compress_format_loading(self): def test_compress_format_loading(self):
# Load fixture 4 (compressed), using format specification # Load fixture 4 (compressed), using format specification

View File

@ -472,8 +472,8 @@ u'entertainment'
u'Entertainment' u'Entertainment'
>>> f.cleaned_data['slug'] >>> f.cleaned_data['slug']
u'entertainment' u'entertainment'
>>> obj = f.save() >>> c1 = f.save()
>>> obj >>> c1
<Category: Entertainment> <Category: Entertainment>
>>> Category.objects.all() >>> Category.objects.all()
[<Category: Entertainment>] [<Category: Entertainment>]
@ -487,8 +487,8 @@ u'test'
u"It's a test" u"It's a test"
>>> f.cleaned_data['slug'] >>> f.cleaned_data['slug']
u'its-test' u'its-test'
>>> obj = f.save() >>> c2 = f.save()
>>> obj >>> c2
<Category: It's a test> <Category: It's a test>
>>> Category.objects.order_by('name') >>> Category.objects.order_by('name')
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
@ -505,12 +505,12 @@ u'third'
u'Third test' u'Third test'
>>> f.cleaned_data['slug'] >>> f.cleaned_data['slug']
u'third-test' u'third-test'
>>> obj = f.save(commit=False) >>> c3 = f.save(commit=False)
>>> obj >>> c3
<Category: Third test> <Category: Third test>
>>> Category.objects.order_by('name') >>> Category.objects.order_by('name')
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
>>> obj.save() >>> c3.save()
>>> Category.objects.order_by('name') >>> Category.objects.order_by('name')
[<Category: Entertainment>, <Category: It's a test>, <Category: Third test>] [<Category: Entertainment>, <Category: It's a test>, <Category: Third test>]
@ -563,9 +563,9 @@ fields with the 'choices' attribute are represented by a ChoiceField.
<option value="3">Live</option> <option value="3">Live</option>
</select></td></tr> </select></td></tr>
<tr><th>Categories:</th><td><select multiple="multiple" name="categories"> <tr><th>Categories:</th><td><select multiple="multiple" name="categories">
<option value="1">Entertainment</option> <option value="...">Entertainment</option>
<option value="2">It&#39;s a test</option> <option value="...">It&#39;s a test</option>
<option value="3">Third test</option> <option value="...">Third test</option>
</select><br /><span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></td></tr> </select><br /><span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></td></tr>
You can restrict a form to a subset of the complete list of fields You can restrict a form to a subset of the complete list of fields
@ -595,8 +595,9 @@ inserted as 'initial' data in each Field.
>>> art = Article(headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=w, article='Hello.') >>> art = Article(headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=w, article='Hello.')
>>> art.save() >>> art.save()
>>> art.id >>> art_id_1 = art.id
1 >>> art_id_1 is not None
True
>>> class TestArticleForm(ModelForm): >>> class TestArticleForm(ModelForm):
... class Meta: ... class Meta:
... model = Article ... model = Article
@ -618,9 +619,9 @@ inserted as 'initial' data in each Field.
<option value="3">Live</option> <option value="3">Live</option>
</select></li> </select></li>
<li>Categories: <select multiple="multiple" name="categories"> <li>Categories: <select multiple="multiple" name="categories">
<option value="1">Entertainment</option> <option value="...">Entertainment</option>
<option value="2">It&#39;s a test</option> <option value="...">It&#39;s a test</option>
<option value="3">Third test</option> <option value="...">Third test</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
>>> f = TestArticleForm({'headline': u'Test headline', 'slug': 'test-headline', 'pub_date': u'1984-02-06', 'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=art) >>> f = TestArticleForm({'headline': u'Test headline', 'slug': 'test-headline', 'pub_date': u'1984-02-06', 'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=art)
>>> f.errors >>> f.errors
@ -628,9 +629,9 @@ inserted as 'initial' data in each Field.
>>> f.is_valid() >>> f.is_valid()
True True
>>> test_art = f.save() >>> test_art = f.save()
>>> test_art.id >>> test_art.id == art_id_1
1 True
>>> test_art = Article.objects.get(id=1) >>> test_art = Article.objects.get(id=art_id_1)
>>> test_art.headline >>> test_art.headline
u'Test headline' u'Test headline'
@ -648,9 +649,9 @@ by specifying a 'fields' argument to form_for_instance.
>>> f.is_valid() >>> f.is_valid()
True True
>>> new_art = f.save() >>> new_art = f.save()
>>> new_art.id >>> new_art.id == art_id_1
1 True
>>> new_art = Article.objects.get(id=1) >>> new_art = Article.objects.get(id=art_id_1)
>>> new_art.headline >>> new_art.headline
u'New headline' u'New headline'
@ -681,13 +682,13 @@ Add some categories and test the many-to-many form output.
<option value="3">Live</option> <option value="3">Live</option>
</select></li> </select></li>
<li>Categories: <select multiple="multiple" name="categories"> <li>Categories: <select multiple="multiple" name="categories">
<option value="1" selected="selected">Entertainment</option> <option value="..." selected="selected">Entertainment</option>
<option value="2">It&#39;s a test</option> <option value="...">It&#39;s a test</option>
<option value="3">Third test</option> <option value="...">Third test</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
Initial values can be provided for model forms Initial values can be provided for model forms
>>> f = TestArticleForm(auto_id=False, initial={'headline': 'Your headline here', 'categories': ['1','2']}) >>> f = TestArticleForm(auto_id=False, initial={'headline': 'Your headline here', 'categories': [str(c1.id), str(c2.id)]})
>>> print f.as_ul() >>> print f.as_ul()
<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li> <li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li>
<li>Slug: <input type="text" name="slug" maxlength="50" /></li> <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
@ -705,17 +706,17 @@ Initial values can be provided for model forms
<option value="3">Live</option> <option value="3">Live</option>
</select></li> </select></li>
<li>Categories: <select multiple="multiple" name="categories"> <li>Categories: <select multiple="multiple" name="categories">
<option value="1" selected="selected">Entertainment</option> <option value="..." selected="selected">Entertainment</option>
<option value="2" selected="selected">It&#39;s a test</option> <option value="..." selected="selected">It&#39;s a test</option>
<option value="3">Third test</option> <option value="...">Third test</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
>>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04', >>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04',
... 'writer': unicode(w_royko.pk), 'article': u'Hello.', 'categories': [u'1', u'2']}, instance=new_art) ... 'writer': unicode(w_royko.pk), 'article': u'Hello.', 'categories': [unicode(c1.id), unicode(c2.id)]}, instance=new_art)
>>> new_art = f.save() >>> new_art = f.save()
>>> new_art.id >>> new_art.id == art_id_1
1 True
>>> new_art = Article.objects.get(id=1) >>> new_art = Article.objects.get(id=art_id_1)
>>> new_art.categories.order_by('name') >>> new_art.categories.order_by('name')
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
@ -723,9 +724,9 @@ Now, submit form data with no categories. This deletes the existing categories.
>>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04', >>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04',
... 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art) ... 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art)
>>> new_art = f.save() >>> new_art = f.save()
>>> new_art.id >>> new_art.id == art_id_1
1 True
>>> new_art = Article.objects.get(id=1) >>> new_art = Article.objects.get(id=art_id_1)
>>> new_art.categories.all() >>> new_art.categories.all()
[] []
@ -734,11 +735,12 @@ Create a new article, with categories, via the form.
... class Meta: ... class Meta:
... model = Article ... model = Article
>>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']}) ... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
>>> new_art = f.save() >>> new_art = f.save()
>>> new_art.id >>> art_id_2 = new_art.id
2 >>> art_id_2 not in (None, art_id_1)
>>> new_art = Article.objects.get(id=2) True
>>> new_art = Article.objects.get(id=art_id_2)
>>> new_art.categories.order_by('name') >>> new_art.categories.order_by('name')
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
@ -749,9 +751,10 @@ Create a new article, with no categories, via the form.
>>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01', >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
... 'writer': unicode(w_royko.pk), 'article': u'Test.'}) ... 'writer': unicode(w_royko.pk), 'article': u'Test.'})
>>> new_art = f.save() >>> new_art = f.save()
>>> new_art.id >>> art_id_3 = new_art.id
3 >>> art_id_3 not in (None, art_id_1, art_id_2)
>>> new_art = Article.objects.get(id=3) True
>>> new_art = Article.objects.get(id=art_id_3)
>>> new_art.categories.all() >>> new_art.categories.all()
[] []
@ -761,16 +764,17 @@ The m2m data won't be saved until save_m2m() is invoked on the form.
... class Meta: ... class Meta:
... model = Article ... model = Article
>>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01', >>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01',
... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']}) ... 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
>>> new_art = f.save(commit=False) >>> new_art = f.save(commit=False)
# Manually save the instance # Manually save the instance
>>> new_art.save() >>> new_art.save()
>>> new_art.id >>> art_id_4 = new_art.id
4 >>> art_id_4 not in (None, art_id_1, art_id_2, art_id_3)
True
# The instance doesn't have m2m data yet # The instance doesn't have m2m data yet
>>> new_art = Article.objects.get(id=4) >>> new_art = Article.objects.get(id=art_id_4)
>>> new_art.categories.all() >>> new_art.categories.all()
[] []
@ -789,12 +793,12 @@ existing Category instance.
>>> cat = Category.objects.get(name='Third test') >>> cat = Category.objects.get(name='Third test')
>>> cat >>> cat
<Category: Third test> <Category: Third test>
>>> cat.id >>> cat.id == c3.id
3 True
>>> form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) >>> form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat)
>>> form.save() >>> form.save()
<Category: Third> <Category: Third>
>>> Category.objects.get(id=3) >>> Category.objects.get(id=c3.id)
<Category: Third> <Category: Third>
Here, we demonstrate that choices for a ForeignKey ChoiceField are determined Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
@ -821,11 +825,12 @@ the data in the database when the form is instantiated.
<option value="3">Live</option> <option value="3">Live</option>
</select></li> </select></li>
<li>Categories: <select multiple="multiple" name="categories"> <li>Categories: <select multiple="multiple" name="categories">
<option value="1">Entertainment</option> <option value="...">Entertainment</option>
<option value="2">It&#39;s a test</option> <option value="...">It&#39;s a test</option>
<option value="3">Third</option> <option value="...">Third</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
>>> Category.objects.create(name='Fourth', url='4th') >>> c4 = Category.objects.create(name='Fourth', url='4th')
>>> c4
<Category: Fourth> <Category: Fourth>
>>> Writer.objects.create(name='Carl Bernstein') >>> Writer.objects.create(name='Carl Bernstein')
<Writer: Carl Bernstein> <Writer: Carl Bernstein>
@ -847,10 +852,10 @@ the data in the database when the form is instantiated.
<option value="3">Live</option> <option value="3">Live</option>
</select></li> </select></li>
<li>Categories: <select multiple="multiple" name="categories"> <li>Categories: <select multiple="multiple" name="categories">
<option value="1">Entertainment</option> <option value="...">Entertainment</option>
<option value="2">It&#39;s a test</option> <option value="...">It&#39;s a test</option>
<option value="3">Third</option> <option value="...">Third</option>
<option value="4">Fourth</option> <option value="...">Fourth</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li> </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
# ModelChoiceField ############################################################ # ModelChoiceField ############################################################
@ -859,7 +864,7 @@ the data in the database when the form is instantiated.
>>> f = ModelChoiceField(Category.objects.all()) >>> f = ModelChoiceField(Category.objects.all())
>>> list(f.choices) >>> list(f.choices)
[(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')] [(u'', u'---------'), (..., u'Entertainment'), (..., u"It's a test"), (..., u'Third'), (..., u'Fourth')]
>>> f.clean('') >>> f.clean('')
Traceback (most recent call last): Traceback (most recent call last):
... ...
@ -872,33 +877,34 @@ ValidationError: [u'This field is required.']
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
>>> f.clean(3) >>> f.clean(c3.id)
<Category: Third> <Category: Third>
>>> f.clean(2) >>> f.clean(c2.id)
<Category: It's a test> <Category: It's a test>
# Add a Category object *after* the ModelChoiceField has already been # Add a Category object *after* the ModelChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather # instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation. # than caching it at time of instantiation.
>>> Category.objects.create(name='Fifth', url='5th') >>> c5 = Category.objects.create(name='Fifth', url='5th')
>>> c5
<Category: Fifth> <Category: Fifth>
>>> f.clean(5) >>> f.clean(c5.id)
<Category: Fifth> <Category: Fifth>
# Delete a Category object *after* the ModelChoiceField has already been # Delete a Category object *after* the ModelChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather # instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation. # than caching it at time of instantiation.
>>> Category.objects.get(url='5th').delete() >>> Category.objects.get(url='5th').delete()
>>> f.clean(5) >>> f.clean(c5.id)
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
>>> f = ModelChoiceField(Category.objects.filter(pk=1), required=False) >>> f = ModelChoiceField(Category.objects.filter(pk=c1.id), required=False)
>>> print f.clean('') >>> print f.clean('')
None None
>>> f.clean('') >>> f.clean('')
>>> f.clean('1') >>> f.clean(str(c1.id))
<Category: Entertainment> <Category: Entertainment>
>>> f.clean('100') >>> f.clean('100')
Traceback (most recent call last): Traceback (most recent call last):
@ -908,10 +914,10 @@ ValidationError: [u'Select a valid choice. That choice is not one of the availab
# queryset can be changed after the field is created. # queryset can be changed after the field is created.
>>> f.queryset = Category.objects.exclude(name='Fourth') >>> f.queryset = Category.objects.exclude(name='Fourth')
>>> list(f.choices) >>> list(f.choices)
[(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] [(u'', u'---------'), (..., u'Entertainment'), (..., u"It's a test"), (..., u'Third')]
>>> f.clean(3) >>> f.clean(c3.id)
<Category: Third> <Category: Third>
>>> f.clean(4) >>> f.clean(c4.id)
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
@ -920,21 +926,21 @@ ValidationError: [u'Select a valid choice. That choice is not one of the availab
>>> gen_one = list(f.choices) >>> gen_one = list(f.choices)
>>> gen_two = f.choices >>> gen_two = f.choices
>>> gen_one[2] >>> gen_one[2]
(2L, u"It's a test") (..., u"It's a test")
>>> list(gen_two) >>> list(gen_two)
[(u'', u'---------'), (1L, u'Entertainment'), (2L, u"It's a test"), (3L, u'Third')] [(u'', u'---------'), (..., u'Entertainment'), (..., u"It's a test"), (..., u'Third')]
# check that we can override the label_from_instance method to print custom labels (#4620) # check that we can override the label_from_instance method to print custom labels (#4620)
>>> f.queryset = Category.objects.all() >>> f.queryset = Category.objects.all()
>>> f.label_from_instance = lambda obj: "category " + str(obj) >>> f.label_from_instance = lambda obj: "category " + str(obj)
>>> list(f.choices) >>> list(f.choices)
[(u'', u'---------'), (1L, 'category Entertainment'), (2L, "category It's a test"), (3L, 'category Third'), (4L, 'category Fourth')] [(u'', u'---------'), (..., 'category Entertainment'), (..., "category It's a test"), (..., 'category Third'), (..., 'category Fourth')]
# ModelMultipleChoiceField #################################################### # ModelMultipleChoiceField ####################################################
>>> f = ModelMultipleChoiceField(Category.objects.all()) >>> f = ModelMultipleChoiceField(Category.objects.all())
>>> list(f.choices) >>> list(f.choices)
[(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')] [(..., u'Entertainment'), (..., u"It's a test"), (..., u'Third'), (..., u'Fourth')]
>>> f.clean(None) >>> f.clean(None)
Traceback (most recent call last): Traceback (most recent call last):
... ...
@ -943,17 +949,17 @@ ValidationError: [u'This field is required.']
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'This field is required.'] ValidationError: [u'This field is required.']
>>> f.clean([1]) >>> f.clean([c1.id])
[<Category: Entertainment>] [<Category: Entertainment>]
>>> f.clean([2]) >>> f.clean([c2.id])
[<Category: It's a test>] [<Category: It's a test>]
>>> f.clean(['1']) >>> f.clean([str(c1.id)])
[<Category: Entertainment>] [<Category: Entertainment>]
>>> f.clean(['1', '2']) >>> f.clean([str(c1.id), str(c2.id)])
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
>>> f.clean([1, '2']) >>> f.clean([c1.id, str(c2.id)])
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
>>> f.clean((1, '2')) >>> f.clean((c1.id, str(c2.id)))
[<Category: Entertainment>, <Category: It's a test>] [<Category: Entertainment>, <Category: It's a test>]
>>> f.clean(['100']) >>> f.clean(['100'])
Traceback (most recent call last): Traceback (most recent call last):
@ -971,16 +977,17 @@ ValidationError: [u'"fail" is not a valid value for a primary key.']
# Add a Category object *after* the ModelMultipleChoiceField has already been # Add a Category object *after* the ModelMultipleChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather # instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation. # than caching it at time of instantiation.
>>> Category.objects.create(id=6, name='Sixth', url='6th') >>> c6 = Category.objects.create(id=6, name='Sixth', url='6th')
>>> c6
<Category: Sixth> <Category: Sixth>
>>> f.clean([6]) >>> f.clean([c6.id])
[<Category: Sixth>] [<Category: Sixth>]
# Delete a Category object *after* the ModelMultipleChoiceField has already been # Delete a Category object *after* the ModelMultipleChoiceField has already been
# instantiated. This proves clean() checks the database during clean() rather # instantiated. This proves clean() checks the database during clean() rather
# than caching it at time of instantiation. # than caching it at time of instantiation.
>>> Category.objects.get(url='6th').delete() >>> Category.objects.get(url='6th').delete()
>>> f.clean([6]) >>> f.clean([c6.id])
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 6 is not one of the available choices.'] ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
@ -994,11 +1001,11 @@ ValidationError: [u'Select a valid choice. 6 is not one of the available choices
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
>>> f.clean(['3', '10']) >>> f.clean([str(c3.id), '10'])
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
>>> f.clean(['1', '10']) >>> f.clean([str(c1.id), '10'])
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 10 is not one of the available choices.'] ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
@ -1006,22 +1013,22 @@ ValidationError: [u'Select a valid choice. 10 is not one of the available choice
# queryset can be changed after the field is created. # queryset can be changed after the field is created.
>>> f.queryset = Category.objects.exclude(name='Fourth') >>> f.queryset = Category.objects.exclude(name='Fourth')
>>> list(f.choices) >>> list(f.choices)
[(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] [(..., u'Entertainment'), (..., u"It's a test"), (..., u'Third')]
>>> f.clean([3]) >>> f.clean([c3.id])
[<Category: Third>] [<Category: Third>]
>>> f.clean([4]) >>> f.clean([c4.id])
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 4 is not one of the available choices.'] ValidationError: [u'Select a valid choice. ... is not one of the available choices.']
>>> f.clean(['3', '4']) >>> f.clean([str(c3.id), str(c4.id)])
Traceback (most recent call last): Traceback (most recent call last):
... ...
ValidationError: [u'Select a valid choice. 4 is not one of the available choices.'] ValidationError: [u'Select a valid choice. ... is not one of the available choices.']
>>> f.queryset = Category.objects.all() >>> f.queryset = Category.objects.all()
>>> f.label_from_instance = lambda obj: "multicategory " + str(obj) >>> f.label_from_instance = lambda obj: "multicategory " + str(obj)
>>> list(f.choices) >>> list(f.choices)
[(1L, 'multicategory Entertainment'), (2L, "multicategory It's a test"), (3L, 'multicategory Third'), (4L, 'multicategory Fourth')] [(..., 'multicategory Entertainment'), (..., "multicategory It's a test"), (..., 'multicategory Third'), (..., 'multicategory Fourth')]
# OneToOneField ############################################################### # OneToOneField ###############################################################

View File

@ -39,11 +39,11 @@ class ProxyModelTests(TestCase):
""" """
Creating a Person makes them accessible through the MyPerson proxy. Creating a Person makes them accessible through the MyPerson proxy.
""" """
Person.objects.create(name="Foo McBar") person = Person.objects.create(name="Foo McBar")
self.assertEqual(len(Person.objects.all()), 1) self.assertEqual(len(Person.objects.all()), 1)
self.assertEqual(len(MyPerson.objects.all()), 1) self.assertEqual(len(MyPerson.objects.all()), 1)
self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, 1) self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, person.id)
self.assertFalse(MyPerson.objects.get(id=1).has_special_name()) self.assertFalse(MyPerson.objects.get(id=person.id).has_special_name())
def test_no_proxy(self): def test_no_proxy(self):
""" """

View File

@ -36,7 +36,7 @@ class ChangeListTests(TransactionTestCase):
template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
context = Context({'cl': cl}) context = Context({'cl': cl})
table_output = template.render(context) table_output = template.render(context)
row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td class="nowrap">(None)</td></tr></tbody>' row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="%d" name="_selected_action" /></td><th><a href="%d/">name</a></th><td class="nowrap">(None)</td></tr></tbody>' % (new_child.id, new_child.id)
self.assertFalse(table_output.find(row_html) == -1, self.assertFalse(table_output.find(row_html) == -1,
'Failed to find expected row element: %s' % table_output) 'Failed to find expected row element: %s' % table_output)
@ -57,7 +57,7 @@ class ChangeListTests(TransactionTestCase):
template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}')
context = Context({'cl': cl}) context = Context({'cl': cl})
table_output = template.render(context) table_output = template.render(context)
row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="1" name="_selected_action" /></td><th><a href="1/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' row_html = '<tbody><tr class="row1"><td class="action-checkbox"><input type="checkbox" class="action-select" value="%d" name="_selected_action" /></td><th><a href="%d/">name</a></th><td class="nowrap">Parent object</td></tr></tbody>' % (new_child.id, new_child.id)
self.assertFalse(table_output.find(row_html) == -1, self.assertFalse(table_output.find(row_html) == -1,
'Failed to find expected row element: %s' % table_output) 'Failed to find expected row element: %s' % table_output)
@ -88,7 +88,7 @@ class ChangeListTests(TransactionTestCase):
context = Context({'cl': cl}) context = Context({'cl': cl})
table_output = template.render(context) table_output = template.render(context)
# make sure that hidden fields are in the correct place # make sure that hidden fields are in the correct place
hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></div>' hiddenfields_div = '<div class="hiddenfields"><input type="hidden" name="form-0-id" value="%d" id="id_form-0-id" /></div>' % new_child.id
self.assertFalse(table_output.find(hiddenfields_div) == -1, self.assertFalse(table_output.find(hiddenfields_div) == -1,
'Failed to find hidden fields in: %s' % table_output) 'Failed to find hidden fields in: %s' % table_output)
# make sure that list editable fields are rendered in divs correctly # make sure that list editable fields are rendered in divs correctly
@ -148,12 +148,12 @@ class ChangeListTests(TransactionTestCase):
band.genres.add(blues) band.genres.add(blues)
m = BandAdmin(Band, admin.site) m = BandAdmin(Band, admin.site)
cl = ChangeList(MockFilteredRequestA(), Band, m.list_display, cl = ChangeList(MockFilteredRequestA(blues.pk), Band, m.list_display,
m.list_display_links, m.list_filter, m.date_hierarchy, m.list_display_links, m.list_filter, m.date_hierarchy,
m.search_fields, m.list_select_related, m.list_per_page, m.search_fields, m.list_select_related, m.list_per_page,
m.list_editable, m) m.list_editable, m)
cl.get_results(MockFilteredRequestA()) cl.get_results(MockFilteredRequestA(blues.pk))
# There's only one Group instance # There's only one Group instance
self.assertEqual(cl.result_count, 1) self.assertEqual(cl.result_count, 1)
@ -169,12 +169,12 @@ class ChangeListTests(TransactionTestCase):
Membership.objects.create(group=band, music=lead, role='bass player') Membership.objects.create(group=band, music=lead, role='bass player')
m = GroupAdmin(Group, admin.site) m = GroupAdmin(Group, admin.site)
cl = ChangeList(MockFilteredRequestB(), Group, m.list_display, cl = ChangeList(MockFilteredRequestB(lead.pk), Group, m.list_display,
m.list_display_links, m.list_filter, m.date_hierarchy, m.list_display_links, m.list_filter, m.date_hierarchy,
m.search_fields, m.list_select_related, m.list_per_page, m.search_fields, m.list_select_related, m.list_per_page,
m.list_editable, m) m.list_editable, m)
cl.get_results(MockFilteredRequestB()) cl.get_results(MockFilteredRequestB(lead.pk))
# There's only one Group instance # There's only one Group instance
self.assertEqual(cl.result_count, 1) self.assertEqual(cl.result_count, 1)
@ -191,12 +191,12 @@ class ChangeListTests(TransactionTestCase):
Membership.objects.create(group=four, music=lead, role='guitar player') Membership.objects.create(group=four, music=lead, role='guitar player')
m = QuartetAdmin(Quartet, admin.site) m = QuartetAdmin(Quartet, admin.site)
cl = ChangeList(MockFilteredRequestB(), Quartet, m.list_display, cl = ChangeList(MockFilteredRequestB(lead.pk), Quartet, m.list_display,
m.list_display_links, m.list_filter, m.date_hierarchy, m.list_display_links, m.list_filter, m.date_hierarchy,
m.search_fields, m.list_select_related, m.list_per_page, m.search_fields, m.list_select_related, m.list_per_page,
m.list_editable, m) m.list_editable, m)
cl.get_results(MockFilteredRequestB()) cl.get_results(MockFilteredRequestB(lead.pk))
# There's only one Quartet instance # There's only one Quartet instance
self.assertEqual(cl.result_count, 1) self.assertEqual(cl.result_count, 1)
@ -213,12 +213,12 @@ class ChangeListTests(TransactionTestCase):
Invitation.objects.create(band=three, player=lead, instrument='bass') Invitation.objects.create(band=three, player=lead, instrument='bass')
m = ChordsBandAdmin(ChordsBand, admin.site) m = ChordsBandAdmin(ChordsBand, admin.site)
cl = ChangeList(MockFilteredRequestB(), ChordsBand, m.list_display, cl = ChangeList(MockFilteredRequestB(lead.pk), ChordsBand, m.list_display,
m.list_display_links, m.list_filter, m.date_hierarchy, m.list_display_links, m.list_filter, m.date_hierarchy,
m.search_fields, m.list_select_related, m.list_per_page, m.search_fields, m.list_select_related, m.list_per_page,
m.list_editable, m) m.list_editable, m)
cl.get_results(MockFilteredRequestB()) cl.get_results(MockFilteredRequestB(lead.pk))
# There's only one ChordsBand instance # There's only one ChordsBand instance
self.assertEqual(cl.result_count, 1) self.assertEqual(cl.result_count, 1)
@ -289,7 +289,9 @@ class ChordsBandAdmin(admin.ModelAdmin):
list_filter = ['members'] list_filter = ['members']
class MockFilteredRequestA(object): class MockFilteredRequestA(object):
GET = { 'genres': 1 } def __init__(self, pk):
self.GET = { 'genres' : pk }
class MockFilteredRequestB(object): class MockFilteredRequestB(object):
GET = { 'members': 1 } def __init__(self, pk):
self.GET = { 'members': pk }

View File

@ -349,7 +349,7 @@ class TestFixtures(TestCase):
""" """
stdout = StringIO() stdout = StringIO()
# Create an instance of the concrete class # Create an instance of the concrete class
Widget(name='grommet').save() widget = Widget.objects.create(name='grommet')
management.call_command( management.call_command(
'dumpdata', 'dumpdata',
'fixtures_regress.widget', 'fixtures_regress.widget',
@ -359,7 +359,8 @@ class TestFixtures(TestCase):
) )
self.assertEqual( self.assertEqual(
stdout.getvalue(), stdout.getvalue(),
"""[{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]"""
% widget.pk
) )

View File

@ -116,8 +116,8 @@ class ForeignKeyTests(test.TestCase):
bar_b = Bar.objects.create(b='bla', a=b) bar_b = Bar.objects.create(b='bla', a=b)
form = BazForm() form = BazForm()
fk_field = str(form['foo']) fk_field = str(form['foo'])
self.assertEqual(len(re.findall(r'value="2"', fk_field)), 0) self.assertEqual(len(re.findall(r'value="%d"' % b.pk, fk_field)), 0)
self.assertEqual(len(re.findall(r'value="1"', fk_field)), 1) self.assertEqual(len(re.findall(r'value="%d"' % a.pk, fk_field)), 1)
class DateTimeFieldTests(unittest.TestCase): class DateTimeFieldTests(unittest.TestCase):
def test_datetimefield_to_python_usecs(self): def test_datetimefield_to_python_usecs(self):

View File

@ -18,11 +18,10 @@ class ModelMultipleChoiceFieldTests(TestCase):
Test that ModelMultipleChoiceField does O(1) queries instead of Test that ModelMultipleChoiceField does O(1) queries instead of
O(n) (#10156). O(n) (#10156).
""" """
for i in range(30): persons = [Person.objects.create(name="Person %s" % i) for i in range(30)]
Person.objects.create(name="Person %s" % i)
f = forms.ModelMultipleChoiceField(queryset=Person.objects.all()) f = forms.ModelMultipleChoiceField(queryset=Person.objects.all())
self.assertNumQueries(1, f.clean, [1, 3, 5, 7, 9]) self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
def test_model_multiple_choice_run_validators(self): def test_model_multiple_choice_run_validators(self):
""" """
@ -126,19 +125,20 @@ class ManyToManyCallableInitialTests(TestCase):
return db_field.formfield(**kwargs) return db_field.formfield(**kwargs)
# Set up some Publications to use as data # Set up some Publications to use as data
Publication(title="First Book", date_published=date(2007,1,1)).save() book1 = Publication.objects.create(title="First Book", date_published=date(2007,1,1))
Publication(title="Second Book", date_published=date(2008,1,1)).save() book2 = Publication.objects.create(title="Second Book", date_published=date(2008,1,1))
Publication(title="Third Book", date_published=date(2009,1,1)).save() book3 = Publication.objects.create(title="Third Book", date_published=date(2009,1,1))
# Create a ModelForm, instantiate it, and check that the output is as expected # Create a ModelForm, instantiate it, and check that the output is as expected
ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield) ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield)
form = ModelForm() form = ModelForm()
self.assertEqual(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li> self.assertEqual(form.as_ul(), u"""<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="100" /></li>
<li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications"> <li><label for="id_publications">Publications:</label> <select multiple="multiple" name="publications" id="id_publications">
<option value="1" selected="selected">First Book</option> <option value="%d" selected="selected">First Book</option>
<option value="2" selected="selected">Second Book</option> <option value="%d" selected="selected">Second Book</option>
<option value="3">Third Book</option> <option value="%d">Third Book</option>
</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>""") </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>"""
% (book1.pk, book2.pk, book3.pk))
class CFFForm(forms.ModelForm): class CFFForm(forms.ModelForm):
class Meta: class Meta:

View File

@ -16,15 +16,15 @@ class NullFkTests(TestCase):
# set of fields will properly LEFT JOIN multiple levels of NULLs (and the things # set of fields will properly LEFT JOIN multiple levels of NULLs (and the things
# that come after the NULLs, or else data that should exist won't). Regression # that come after the NULLs, or else data that should exist won't). Regression
# test for #7369. # test for #7369.
c = Comment.objects.select_related().get(id=1) c = Comment.objects.select_related().get(id=c1.id)
self.assertEqual(c.post, p) self.assertEqual(c.post, p)
self.assertEqual(Comment.objects.select_related().get(id=2).post, None) self.assertEqual(Comment.objects.select_related().get(id=c2.id).post, None)
self.assertQuerysetEqual( self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info').all(), Comment.objects.select_related('post__forum__system_info').all(),
[ [
(1, u'My first comment', '<Post: First Post>'), (c1.id, u'My first comment', '<Post: First Post>'),
(2, u'My second comment', 'None') (c2.id, u'My second comment', 'None')
], ],
transform = lambda c: (c.id, c.comment_text, repr(c.post)) transform = lambda c: (c.id, c.comment_text, repr(c.post))
) )
@ -35,8 +35,8 @@ class NullFkTests(TestCase):
self.assertQuerysetEqual( self.assertQuerysetEqual(
Comment.objects.select_related('post__forum__system_info__system_details'), Comment.objects.select_related('post__forum__system_info__system_details'),
[ [
(1, u'My first comment', '<Post: First Post>'), (c1.id, u'My first comment', '<Post: First Post>'),
(2, u'My second comment', 'None') (c2.id, u'My second comment', 'None')
], ],
transform = lambda c: (c.id, c.comment_text, repr(c.post)) transform = lambda c: (c.id, c.comment_text, repr(c.post))
) )

View File

@ -28,11 +28,11 @@ class SelectRelatedRegressTests(TestCase):
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id') connections=Connection.objects.filter(start__device__building=b, end__device__building=b).order_by('id')
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections], self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
[(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')]) [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')])
connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id') connections=Connection.objects.filter(start__device__building=b, end__device__building=b).select_related().order_by('id')
self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections], self.assertEqual([(c.id, unicode(c.start), unicode(c.end)) for c in connections],
[(1, u'router/4', u'switch/7'), (2, u'switch/7', u'server/1')]) [(c1.id, u'router/4', u'switch/7'), (c2.id, u'switch/7', u'server/1')])
# This final query should only join seven tables (port, device and building # This final query should only join seven tables (port, device and building
# twice each, plus connection once). # twice each, plus connection once).