diff --git a/django/contrib/flatpages/tests/forms.py b/django/contrib/flatpages/tests/forms.py index 969d347b392..e8ca2b8e5c2 100644 --- a/django/contrib/flatpages/tests/forms.py +++ b/django/contrib/flatpages/tests/forms.py @@ -1,3 +1,4 @@ +from django.conf import settings from django.contrib.flatpages.admin import FlatpageForm from django.test import TestCase @@ -6,7 +7,7 @@ class FlatpageAdminFormTests(TestCase): self.form_data = { 'title': "A test page", 'content': "This is a test", - 'sites': [1], + 'sites': [settings.SITE_ID], } def test_flatpage_admin_form_url_validation(self): diff --git a/django/contrib/flatpages/tests/views.py b/django/contrib/flatpages/tests/views.py index a8853bc883a..4452745393f 100644 --- a/django/contrib/flatpages/tests/views.py +++ b/django/contrib/flatpages/tests/views.py @@ -68,7 +68,7 @@ class FlatpageViewTests(TestCase): enable_comments=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/') self.assertEqual(response.status_code, 200) diff --git a/tests/modeltests/field_subclassing/tests.py b/tests/modeltests/field_subclassing/tests.py index 25f51600b93..ee32384f0c7 100644 --- a/tests/modeltests/field_subclassing/tests.py +++ b/tests/modeltests/field_subclassing/tests.py @@ -55,7 +55,7 @@ class CustomField(TestCase): # Serialization works, too. 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] self.assertEqual(obj.object, m) diff --git a/tests/modeltests/fixtures/tests.py b/tests/modeltests/fixtures/tests.py index 3c08e268673..31f72f02ca4 100644 --- a/tests/modeltests/fixtures/tests.py +++ b/tests/modeltests/fixtures/tests.py @@ -2,6 +2,7 @@ import StringIO import sys from django.conf import settings +from django.contrib.sites.models import Site from django.core import management from django.db import DEFAULT_DB_ALIAS from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature @@ -45,6 +46,7 @@ class FixtureLoadingTests(TestCase): def test_loading_and_dumping(self): new_io = StringIO.StringIO() + Site.objects.all().delete() # Load fixture 1. Single JSON file, with two objects. management.call_command('loaddata', 'fixture1.json', verbosity=0, commit=False) self.assertQuerysetEqual(Article.objects.all(), [ @@ -159,6 +161,7 @@ class FixtureLoadingTests(TestCase): def test_dumpdata_with_excludes(self): # 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) # Excluding fixtures app should only leave sites @@ -200,15 +203,15 @@ class FixtureLoadingTests(TestCase): exclude_list=['fixtures.FooModel']) def test_dumpdata_with_filtering_manager(self): - Spy(name='Paul').save() - Spy(name='Alex', cover_blown=True).save() + spy1 = Spy.objects.create(name='Paul') + spy2 = Spy.objects.create(name='Alex', cover_blown=True) self.assertQuerysetEqual(Spy.objects.all(), ['']) # 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, # 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): # Load fixture 4 (compressed), using format specification diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index bab0335b8f6..9a962ad72eb 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -472,8 +472,8 @@ u'entertainment' u'Entertainment' >>> f.cleaned_data['slug'] u'entertainment' ->>> obj = f.save() ->>> obj +>>> c1 = f.save() +>>> c1 >>> Category.objects.all() [] @@ -487,8 +487,8 @@ u'test' u"It's a test" >>> f.cleaned_data['slug'] u'its-test' ->>> obj = f.save() ->>> obj +>>> c2 = f.save() +>>> c2 >>> Category.objects.order_by('name') [, ] @@ -505,12 +505,12 @@ u'third' u'Third test' >>> f.cleaned_data['slug'] u'third-test' ->>> obj = f.save(commit=False) ->>> obj +>>> c3 = f.save(commit=False) +>>> c3 >>> Category.objects.order_by('name') [, ] ->>> obj.save() +>>> c3.save() >>> Category.objects.order_by('name') [, , ] @@ -563,9 +563,9 @@ fields with the 'choices' attribute are represented by a ChoiceField. Categories:
Hold down "Control", or "Command" on a Mac, to select more than one. 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.save() ->>> art.id -1 +>>> art_id_1 = art.id +>>> art_id_1 is not None +True >>> class TestArticleForm(ModelForm): ... class Meta: ... model = Article @@ -618,9 +619,9 @@ inserted as 'initial' data in each Field.
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • >>> 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 @@ -628,9 +629,9 @@ inserted as 'initial' data in each Field. >>> f.is_valid() True >>> test_art = f.save() ->>> test_art.id -1 ->>> test_art = Article.objects.get(id=1) +>>> test_art.id == art_id_1 +True +>>> test_art = Article.objects.get(id=art_id_1) >>> test_art.headline u'Test headline' @@ -648,9 +649,9 @@ by specifying a 'fields' argument to form_for_instance. >>> f.is_valid() True >>> new_art = f.save() ->>> new_art.id -1 ->>> new_art = Article.objects.get(id=1) +>>> new_art.id == art_id_1 +True +>>> new_art = Article.objects.get(id=art_id_1) >>> new_art.headline u'New headline' @@ -681,13 +682,13 @@ Add some categories and test the many-to-many form output.
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • 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()
  • Headline:
  • Slug:
  • @@ -705,17 +706,17 @@ Initial values can be provided for model forms
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • >>> 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.id -1 ->>> new_art = Article.objects.get(id=1) +>>> new_art.id == art_id_1 +True +>>> new_art = Article.objects.get(id=art_id_1) >>> new_art.categories.order_by('name') [, ] @@ -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', ... 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art) >>> new_art = f.save() ->>> new_art.id -1 ->>> new_art = Article.objects.get(id=1) +>>> new_art.id == art_id_1 +True +>>> new_art = Article.objects.get(id=art_id_1) >>> new_art.categories.all() [] @@ -734,11 +735,12 @@ Create a new article, with categories, via the form. ... class Meta: ... model = Article >>> 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.id -2 ->>> new_art = Article.objects.get(id=2) +>>> art_id_2 = new_art.id +>>> art_id_2 not in (None, art_id_1) +True +>>> new_art = Article.objects.get(id=art_id_2) >>> new_art.categories.order_by('name') [, ] @@ -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', ... 'writer': unicode(w_royko.pk), 'article': u'Test.'}) >>> new_art = f.save() ->>> new_art.id -3 ->>> new_art = Article.objects.get(id=3) +>>> art_id_3 = new_art.id +>>> art_id_3 not in (None, art_id_1, art_id_2) +True +>>> new_art = Article.objects.get(id=art_id_3) >>> 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: ... model = Article >>> 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) # Manually save the instance >>> new_art.save() ->>> new_art.id -4 +>>> art_id_4 = new_art.id +>>> art_id_4 not in (None, art_id_1, art_id_2, art_id_3) +True # 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() [] @@ -789,12 +793,12 @@ existing Category instance. >>> cat = Category.objects.get(name='Third test') >>> cat ->>> cat.id -3 +>>> cat.id == c3.id +True >>> form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat) >>> form.save() ->>> Category.objects.get(id=3) +>>> Category.objects.get(id=c3.id) 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.
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • ->>> Category.objects.create(name='Fourth', url='4th') +>>> c4 = Category.objects.create(name='Fourth', url='4th') +>>> c4 >>> Writer.objects.create(name='Carl Bernstein') @@ -847,10 +852,10 @@ the data in the database when the form is instantiated.
  • Categories: Hold down "Control", or "Command" on a Mac, to select more than one.
  • # ModelChoiceField ############################################################ @@ -859,7 +864,7 @@ the data in the database when the form is instantiated. >>> f = ModelChoiceField(Category.objects.all()) >>> 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('') Traceback (most recent call last): ... @@ -872,33 +877,34 @@ ValidationError: [u'This field is required.'] Traceback (most recent call last): ... ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] ->>> f.clean(3) +>>> f.clean(c3.id) ->>> f.clean(2) +>>> f.clean(c2.id) # Add a Category object *after* the ModelChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. ->>> Category.objects.create(name='Fifth', url='5th') +>>> c5 = Category.objects.create(name='Fifth', url='5th') +>>> c5 ->>> f.clean(5) +>>> f.clean(c5.id) # Delete a Category object *after* the ModelChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.get(url='5th').delete() ->>> f.clean(5) +>>> f.clean(c5.id) Traceback (most recent call last): ... 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('') None >>> f.clean('') ->>> f.clean('1') +>>> f.clean(str(c1.id)) >>> f.clean('100') 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. >>> f.queryset = Category.objects.exclude(name='Fourth') >>> list(f.choices) -[(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] ->>> f.clean(3) +[(u'', u'---------'), (..., u'Entertainment'), (..., u"It's a test"), (..., u'Third')] +>>> f.clean(c3.id) ->>> f.clean(4) +>>> f.clean(c4.id) Traceback (most recent call last): ... 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_two = f.choices >>> gen_one[2] -(2L, u"It's a test") +(..., u"It's a test") >>> 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) >>> f.queryset = Category.objects.all() >>> f.label_from_instance = lambda obj: "category " + str(obj) >>> 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 #################################################### >>> f = ModelMultipleChoiceField(Category.objects.all()) >>> 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) Traceback (most recent call last): ... @@ -943,17 +949,17 @@ ValidationError: [u'This field is required.'] Traceback (most recent call last): ... ValidationError: [u'This field is required.'] ->>> f.clean([1]) +>>> f.clean([c1.id]) [] ->>> f.clean([2]) +>>> f.clean([c2.id]) [] ->>> f.clean(['1']) +>>> f.clean([str(c1.id)]) [] ->>> f.clean(['1', '2']) +>>> f.clean([str(c1.id), str(c2.id)]) [, ] ->>> f.clean([1, '2']) +>>> f.clean([c1.id, str(c2.id)]) [, ] ->>> f.clean((1, '2')) +>>> f.clean((c1.id, str(c2.id))) [, ] >>> f.clean(['100']) 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 # instantiated. This proves clean() checks the database during clean() rather # 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 ->>> f.clean([6]) +>>> f.clean([c6.id]) [] # Delete a Category object *after* the ModelMultipleChoiceField has already been # instantiated. This proves clean() checks the database during clean() rather # than caching it at time of instantiation. >>> Category.objects.get(url='6th').delete() ->>> f.clean([6]) +>>> f.clean([c6.id]) Traceback (most recent call last): ... 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): ... 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): ... 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): ... 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. >>> f.queryset = Category.objects.exclude(name='Fourth') >>> list(f.choices) -[(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')] ->>> f.clean([3]) +[(..., u'Entertainment'), (..., u"It's a test"), (..., u'Third')] +>>> f.clean([c3.id]) [] ->>> f.clean([4]) +>>> f.clean([c4.id]) Traceback (most recent call last): ... -ValidationError: [u'Select a valid choice. 4 is not one of the available choices.'] ->>> f.clean(['3', '4']) +ValidationError: [u'Select a valid choice. ... is not one of the available choices.'] +>>> f.clean([str(c3.id), str(c4.id)]) 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.label_from_instance = lambda obj: "multicategory " + str(obj) >>> 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 ############################################################### diff --git a/tests/modeltests/proxy_models/tests.py b/tests/modeltests/proxy_models/tests.py index 346a2a3296b..0a46a252c5f 100644 --- a/tests/modeltests/proxy_models/tests.py +++ b/tests/modeltests/proxy_models/tests.py @@ -39,11 +39,11 @@ class ProxyModelTests(TestCase): """ 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(MyPerson.objects.all()), 1) - self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, 1) - self.assertFalse(MyPerson.objects.get(id=1).has_special_name()) + self.assertEqual(MyPerson.objects.get(name="Foo McBar").id, person.id) + self.assertFalse(MyPerson.objects.get(id=person.id).has_special_name()) def test_no_proxy(self): """ diff --git a/tests/regressiontests/admin_changelist/tests.py b/tests/regressiontests/admin_changelist/tests.py index b53d832752c..0e61addc118 100644 --- a/tests/regressiontests/admin_changelist/tests.py +++ b/tests/regressiontests/admin_changelist/tests.py @@ -36,7 +36,7 @@ class ChangeListTests(TransactionTestCase): template = Template('{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}') context = Context({'cl': cl}) table_output = template.render(context) - row_html = 'name(None)' + row_html = 'name(None)' % (new_child.id, new_child.id) self.assertFalse(table_output.find(row_html) == -1, '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 %}') context = Context({'cl': cl}) table_output = template.render(context) - row_html = 'nameParent object' + row_html = 'nameParent object' % (new_child.id, new_child.id) self.assertFalse(table_output.find(row_html) == -1, 'Failed to find expected row element: %s' % table_output) @@ -88,7 +88,7 @@ class ChangeListTests(TransactionTestCase): context = Context({'cl': cl}) table_output = template.render(context) # make sure that hidden fields are in the correct place - hiddenfields_div = '
    ' + hiddenfields_div = '
    ' % new_child.id self.assertFalse(table_output.find(hiddenfields_div) == -1, 'Failed to find hidden fields in: %s' % table_output) # make sure that list editable fields are rendered in divs correctly @@ -148,12 +148,12 @@ class ChangeListTests(TransactionTestCase): band.genres.add(blues) 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.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) - cl.get_results(MockFilteredRequestA()) + cl.get_results(MockFilteredRequestA(blues.pk)) # There's only one Group instance self.assertEqual(cl.result_count, 1) @@ -169,12 +169,12 @@ class ChangeListTests(TransactionTestCase): Membership.objects.create(group=band, music=lead, role='bass player') 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.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) - cl.get_results(MockFilteredRequestB()) + cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one Group instance self.assertEqual(cl.result_count, 1) @@ -191,12 +191,12 @@ class ChangeListTests(TransactionTestCase): Membership.objects.create(group=four, music=lead, role='guitar player') 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.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) - cl.get_results(MockFilteredRequestB()) + cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one Quartet instance self.assertEqual(cl.result_count, 1) @@ -213,12 +213,12 @@ class ChangeListTests(TransactionTestCase): Invitation.objects.create(band=three, player=lead, instrument='bass') 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.search_fields, m.list_select_related, m.list_per_page, m.list_editable, m) - cl.get_results(MockFilteredRequestB()) + cl.get_results(MockFilteredRequestB(lead.pk)) # There's only one ChordsBand instance self.assertEqual(cl.result_count, 1) @@ -289,7 +289,9 @@ class ChordsBandAdmin(admin.ModelAdmin): list_filter = ['members'] class MockFilteredRequestA(object): - GET = { 'genres': 1 } + def __init__(self, pk): + self.GET = { 'genres' : pk } class MockFilteredRequestB(object): - GET = { 'members': 1 } + def __init__(self, pk): + self.GET = { 'members': pk } diff --git a/tests/regressiontests/fixtures_regress/tests.py b/tests/regressiontests/fixtures_regress/tests.py index e7f24585a0a..3dc4edee555 100644 --- a/tests/regressiontests/fixtures_regress/tests.py +++ b/tests/regressiontests/fixtures_regress/tests.py @@ -349,7 +349,7 @@ class TestFixtures(TestCase): """ stdout = StringIO() # Create an instance of the concrete class - Widget(name='grommet').save() + widget = Widget.objects.create(name='grommet') management.call_command( 'dumpdata', 'fixtures_regress.widget', @@ -359,7 +359,8 @@ class TestFixtures(TestCase): ) self.assertEqual( stdout.getvalue(), - """[{"pk": 1, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" + """[{"pk": %d, "model": "fixtures_regress.widget", "fields": {"name": "grommet"}}]""" + % widget.pk ) diff --git a/tests/regressiontests/model_fields/tests.py b/tests/regressiontests/model_fields/tests.py index 134e0c763af..b6d9a3d713d 100644 --- a/tests/regressiontests/model_fields/tests.py +++ b/tests/regressiontests/model_fields/tests.py @@ -116,8 +116,8 @@ class ForeignKeyTests(test.TestCase): bar_b = Bar.objects.create(b='bla', a=b) form = BazForm() fk_field = str(form['foo']) - self.assertEqual(len(re.findall(r'value="2"', fk_field)), 0) - self.assertEqual(len(re.findall(r'value="1"', fk_field)), 1) + self.assertEqual(len(re.findall(r'value="%d"' % b.pk, fk_field)), 0) + self.assertEqual(len(re.findall(r'value="%d"' % a.pk, fk_field)), 1) class DateTimeFieldTests(unittest.TestCase): def test_datetimefield_to_python_usecs(self): diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py index fe1ad21d31b..f53600195b0 100644 --- a/tests/regressiontests/model_forms_regress/tests.py +++ b/tests/regressiontests/model_forms_regress/tests.py @@ -18,11 +18,10 @@ class ModelMultipleChoiceFieldTests(TestCase): Test that ModelMultipleChoiceField does O(1) queries instead of O(n) (#10156). """ - for i in range(30): - Person.objects.create(name="Person %s" % i) + persons = [Person.objects.create(name="Person %s" % i) for i in range(30)] 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): """ @@ -126,19 +125,20 @@ class ManyToManyCallableInitialTests(TestCase): return db_field.formfield(**kwargs) # Set up some Publications to use as data - Publication(title="First Book", date_published=date(2007,1,1)).save() - Publication(title="Second Book", date_published=date(2008,1,1)).save() - Publication(title="Third Book", date_published=date(2009,1,1)).save() + book1 = Publication.objects.create(title="First Book", date_published=date(2007,1,1)) + book2 = Publication.objects.create(title="Second Book", date_published=date(2008,1,1)) + 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 ModelForm = modelform_factory(Article, formfield_callback=formfield_for_dbfield) form = ModelForm() self.assertEqual(form.as_ul(), u"""
  • Hold down "Control", or "Command" on a Mac, to select more than one.
  • """) + + + + Hold down "Control", or "Command" on a Mac, to select more than one.""" + % (book1.pk, book2.pk, book3.pk)) class CFFForm(forms.ModelForm): class Meta: diff --git a/tests/regressiontests/null_fk/tests.py b/tests/regressiontests/null_fk/tests.py index 23f2061475a..ab4bd522a0e 100644 --- a/tests/regressiontests/null_fk/tests.py +++ b/tests/regressiontests/null_fk/tests.py @@ -16,15 +16,15 @@ class NullFkTests(TestCase): # 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 # 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(Comment.objects.select_related().get(id=2).post, None) + self.assertEqual(Comment.objects.select_related().get(id=c2.id).post, None) self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info').all(), [ - (1, u'My first comment', ''), - (2, u'My second comment', 'None') + (c1.id, u'My first comment', ''), + (c2.id, u'My second comment', 'None') ], transform = lambda c: (c.id, c.comment_text, repr(c.post)) ) @@ -35,8 +35,8 @@ class NullFkTests(TestCase): self.assertQuerysetEqual( Comment.objects.select_related('post__forum__system_info__system_details'), [ - (1, u'My first comment', ''), - (2, u'My second comment', 'None') + (c1.id, u'My first comment', ''), + (c2.id, u'My second comment', 'None') ], transform = lambda c: (c.id, c.comment_text, repr(c.post)) ) diff --git a/tests/regressiontests/select_related_regress/tests.py b/tests/regressiontests/select_related_regress/tests.py index b6c46fcd916..ede1385351e 100644 --- a/tests/regressiontests/select_related_regress/tests.py +++ b/tests/regressiontests/select_related_regress/tests.py @@ -28,11 +28,11 @@ class SelectRelatedRegressTests(TestCase): 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], - [(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') 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 # twice each, plus connection once).